I want to set color of the tab text white, i cant find any good tutorial. Can someone help me?
There is my tab activity:
package com.example.dev.nordugrid;
import android.app.TabActivity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.TabHost.TabSpec;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
#SuppressWarnings("deprecation")
public class Busena extends TabActivity {
SharedPreferences prefs;
TextView proxySuteike, proxyGaliojimas;
Button button4;
public int randomInt;
String stringProxyGaliojimas, stringProxySuteike, stringUzduotiesPav, stringUzduotiesJDL, stringKitiFailai;
Button holder;
private ArrayList<Item> m_parts = new ArrayList<Item>();
private Runnable viewParts;
private ItemAdapter m_adapter;
private final String data[] = { "Android", "iPhone", "BlackBerry", "AndroidPeople" };
private final String data2[] = { "Ivykdyta", "Atsaukta", "Einama", "Nusisnekejo" };
List<String> a = new ArrayList<String>();
List<String> b = new ArrayList<String>();
public static void setDefaults(String key, String value, Context context) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = prefs.edit();
editor.putString(key, value);
editor.commit();
}
public static String getDefaults(String key, Context context) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
return preferences.getString(key, null);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
this.setContentView(R.layout.activity_busena);
this.setTheme(R.style.listItem);
holder = (Button)findViewById(R.id.button19);
proxyGaliojimas = (TextView)findViewById(R.id.generatenumber);
proxySuteike = (TextView) findViewById(R.id.textView5);
randomInt = Integer.parseInt(getDefaults("proxy", this));
stringProxySuteike = getDefaults("vo", this);
proxyGaliojimas.setText(randomInt + " min.");
proxySuteike.setText(stringProxySuteike);
stringUzduotiesPav = getDefaults("uzduotiesPav", this);
stringUzduotiesJDL = getDefaults("jdlFailoReiksme", this);
stringKitiFailai = getDefaults("kitiFailaiReiksme", this);
ListView list = (ListView)findViewById(R.id.tab1);
m_parts.add(new Item(stringUzduotiesPav, stringUzduotiesJDL));
m_adapter = new ItemAdapter(this, R.layout.row, m_parts);
list.setAdapter(m_adapter);
button4 = (Button) findViewById(R.id.refreshProxy);
TabHost tabHost = getTabHost();
this.setNewTab(this, tabHost, "tab1", R.string.uzduotys, android.R.drawable.star_on, R.id.tab1);
this.setNewTab(this, tabHost, "tab2", R.string.proxy, android.R.drawable.star_on, R.id.tab2);
addListenerOnButton();
}
/*#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
String item = (String) getListAdapter().getItem(position);
Toast.makeText(this, item + " selected", Toast.LENGTH_LONG).show();
}*/
private void setNewTab(Context context, TabHost tabHost, String tag, int title, int icon, int contentID ) {
TabSpec tabSpec = tabHost.newTabSpec(tag);
String titleString = getString(title);
tabSpec.setIndicator(titleString, context.getResources().getDrawable(android.R.drawable.star_on));
tabSpec.setContent(contentID);
tabHost.addTab(tabSpec);
}
public void addListenerOnButton() {
button4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int skaicius = randomInt;
Random randomGenerator = new Random();
int rand = randomGenerator.nextInt(240-skaicius);
String ats = Integer.toString(randomInt);
proxyGaliojimas.setText(ats + " min.");
randomInt = rand;
}
});
}
}
And this is what I see :
This is tab activity xml file:
<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"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context="com.example.dev.nordugrid.Busena"
android:background="#drawable/background"
>
<TabHost
android:id="#android:id/tabhost"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<TabWidget
android:theme="#style/listItem"
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">
<ListView
android:id="#+id/tab1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" />
<LinearLayout
android:id="#+id/tab2"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<!-- antro tabo vaizdas -->
<TextView
android:layout_marginTop="3dp"
android:id="#+id/textView3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/proxyGaliojimas"
android:textColor="#FFFBFB"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:layout_marginLeft="7dp"
android:layout_marginTop="3dp"
android:id="#+id/generatenumber"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/min"
android:textColor="#FFFBFB"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:layout_marginTop="3dp"
android:id="#+id/textView4"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/proxySuteike"
android:textColor="#FFFBFB"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:layout_marginLeft="7dp"
android:layout_marginTop="3dp"
android:id="#+id/textView5"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/proxySuteike"
android:textColor="#FFFBFB"
android:textAppearance="?android:attr/textAppearanceMedium" />
<Button
android:layout_marginTop="7dp"
android:id="#+id/refreshProxy"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/atnaujinti"
android:textColor="#FFFBFB"
android:background="#drawable/border"/>
</LinearLayout>
</FrameLayout>
</LinearLayout>
</TabHost>
Please someone give me simple example or other help :)
Create this method:-
private static View createTabView(Context context, String tabText) {
View view = LayoutInflater.from(context).inflate(R.layout.custom_tab, null, false);
TextView tv = (TextView) view.findViewById(R.id.tabTitleText);
tv.setText(tabText);
return view;
}
Create custom_tab.xml file in layout folder
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/tabTitleText"
android:layout_width="#dimen/tabWidth"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:clickable="true"
android:paddingTop="#dimen/tabTopPading"
android:paddingBottom="#dimen/tabBottomPading"
android:paddingLeft="#dimen/tabLeftPading"
android:paddingRight="#dimen/tabRightPading"
android:textSize="#dimen/tabTextSize"
android:textColor="#color/themeColor"
android:background="#drawable/tab_selector"/>
finally set
tabHost.newTabSpec("Tab1").setIndicator(createTabView(getApplicationContext(),"Tab_name"))
Related
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 3 years ago.
java.lang.NullPointerException: Attempt to invoke interface method
'boolean java.util.List.add(java.lang.Object)' on a null object
reference
I need to give validation for every edit text of main XML and save button is also scrolling and date is showing in Text view of date,after save that person details should be added to the next screen at top of the List View ,already List view had five defalut person details,i am unable to do this please help me,in List View every items should consists update and delete button ,click on update dailog should open and need to be edited in dailog,delete means delete person details from the listview.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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=".MainActivity">
<ScrollView
android:id="#+id/scroll_view"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:id="#+id/linearlayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="#+id/tv_name1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="30dp"
android:layout_marginTop="15dp"
android:layout_marginRight="30dp"
android:padding="15dp"
android:text="Name:"
android:textSize="15sp" />
<EditText
android:id="#+id/et_name1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="30dp"
android:layout_marginRight="30dp"
android:hint="Enter Your Name"
android:padding="15dp"
android:textSize="15sp" />
<TextView
android:id="#+id/tv_email"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="30dp"
android:layout_marginRight="30dp"
android:padding="15dp"
android:text="Email:"
android:textSize="15dp" />
<EditText
android:id="#+id/et_email"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="30dp"
android:layout_marginRight="30dp"
android:hint="Enter Your Mail"
android:textSize="15dp" />
<TextView
android:id="#+id/tv_phoneno"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="30dp"
android:layout_marginRight="30dp"
android:padding="15dp"
android:text="Phone No:"
android:textSize="15dp" />
<EditText
android:id="#+id/et_phoneno"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="30dp"
android:layout_marginRight="30dp"
android:hint="Enter your Contact No"
android:padding="15dp"
android:textSize="15dp" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:padding="15dp"
android:weightSum="2">
<TextView
android:id="#+id/tv_dob"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginLeft="30dp"
android:layout_marginRight="30dp"
android:layout_weight="1"
android:text="DOB:"
android:textSize="15dp"
/>
<Button
android:id="#+id/datepicker1"
android:layout_width="0dp"
android:layout_height="30dp"
android:layout_marginLeft="30dp"
android:layout_marginRight="70dp"
android:layout_weight="1"
android:textSize="15dp">
</Button>
</LinearLayout>
<TextView
android:id="#+id/tv_qualification"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="30dp"
android:layout_marginRight="30dp"
android:padding="15dp"
android:text="Qualification"
android:textSize="15dp" />
<EditText
android:id="#+id/et_qualification"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="30dp"
android:layout_marginRight="30dp"
android:hint="Enter Your Qualification"
android:padding="15dp"
android:textSize="15dp" />
<LinearLayout
android:id="#+id/linearlayout2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:padding="15dp"
android:weightSum="2">
<TextView
android:id="#+id/tv_time"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginLeft="30dp"
android:layout_marginRight="30dp"
android:layout_weight="1"
android:text="Time:"
android:textSize="15dp"
/>
<Button
android:id="#+id/timepicker1"
android:layout_width="0dp"
android:layout_height="30dp"
android:layout_marginLeft="30dp"
android:layout_marginRight="70dp"
android:layout_weight="1"
android:textSize="15dp">
</Button>
</LinearLayout>
<Button
android:id="#+id/button_save"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Save"
android:layout_gravity="center"
android:textSize="15dp">
</Button>
</LinearLayout>
</ScrollView>
</RelativeLayout
Person.java
package com.example.android.persondetails;
public class Person {
private String name;
private String contactno;
private String email;
private String qualification;
private String datepicker;
private String timepicker;
public Person(String name, String contactno, String email, String qualification, String datepicker, String timepicker) {
this.name = name;
this.contactno = contactno;
this.qualification=qualification;
this.datepicker=datepicker;
this.email=email;
this.timepicker=timepicker;
}
public String getName() {
return name == null ? "" : name;
}
public void setName(String name) {
this.name = name;
}
public String getContactno() {
return contactno;
}
public void setContactno(String contactno){
this.contactno=contactno;
}
public String getEmail() {
return email;
}
public String getQualification() {
return qualification;
}
public String getDatepicker() {
return datepicker;
}
public String getTimepicker() {
return timepicker;
}
}
SecondActivity.java
package com.example.android.persondetails;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
import static java.util.Calendar.AM;
public class SecondActivity extends AppCompatActivity {
private ListView lvContact;
private Button addBtn,dleBtn;
private PersonListAdapter adapter;
private List<Person> mPersonList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second_layout);
ArrayList<Person> mPersonList = new ArrayList<Person>();
addBtn = (Button) findViewById(R.id.update);
dleBtn=(Button)findViewById(R.id.delete);
lvContact = (ListView) findViewById(R.id.listView);
addMethod();
setAdapter();
Intent intent = getIntent();
String text;
text = (String) intent.getStringExtra(MainActivity.EXTRA_NAME);
String text1 = (String) intent.getStringExtra(MainActivity.EXTRA_EMAIL);
String text3 = (String) intent.getStringExtra(MainActivity.EXTRA_PHONE_NUMBER);
String text4 = (String) intent.getStringExtra(MainActivity.EXTRA_DOB);
String text5 = (String) intent.getStringExtra(MainActivity.EXTRA_TIME);
String text2 = (String)intent.getStringExtra(MainActivity.EXTRA_QUALIFICATION);
Log.d("PersonDetails", text + " " + text1 + "" + text2 + "" + text3 + "" + text4 + "" + text5);
}
private void addMethod() {
mPersonList.add(new Person("Narendra", "83330072", "narendraprasad616#gmail.com", "btech", "14 / 06 / 1996", "5-30 AM"));
mPersonList.add(new Person("Banu", "715452", "naredra#gmail.com", "btech", "14 / 06 / 1996", "5-45 AM"));
mPersonList.add(new Person("Kalyan", "83330072", "narendraprad616#gmail.com", "btech", "14 / 06 / 1998", "5-30 AM"));
mPersonList.add(new Person("Teja", "8775564", "narendraprasa16#gmail.com", "btech", "14 / 06 / 1990", "5-30 AM"));
mPersonList.add(new Person("Manu", "86423", "narendraprad616#gmail.com", "btech", "14 / 06 / 1996", "5-30 AM"));
}
private void setAdapter() {
adapter = new PersonListAdapter(SecondActivity.this, mPersonList);
lvContact.setAdapter(adapter);
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.android.persondetails">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme"
>
<activity android:name=".SecondActivity">
</activity>
<activity android:name=".MainActivity"
android:parentActivityName=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
PersonListAdapter.java
package com.example.android.persondetails;
import android.content.Context;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import java.util.List;
public class PersonListAdapter extends BaseAdapter {
private Context mContext;
private List<Person> mPersonList;
PersonListAdapter(Context mContext, List<Person> mPersonList) {
this.mContext = mContext;
this.mPersonList = mPersonList;
}
#Override
public int getCount() {
return mPersonList.size();
}
#Override
public Object getItem(int position) {
return mPersonList.get(position);
}
#RequiresApi(api = Build.VERSION_CODES.P)
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = LayoutInflater.from(mContext).inflate(R.layout.second_layout, parent, false);
holder.tv_name = (TextView) convertView.findViewById(R.id.tv_name1);
holder.tv_contactno = (TextView) convertView.findViewById(R.id.tv_phoneno);
holder.tv_email=(TextView)convertView.findViewById(R.id.tv_email);
holder.tv_dob=(TextView)convertView.findViewById(R.id.tv_dob);
holder.tv_qualification=(TextView)convertView.findViewById(R.id.tv_qualification);
holder.tv_time=(TextView)convertView.findViewById(R.id.tv_time);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.tv_name.setText(mPersonList.get(position).getName());
holder.tv_contactno.setText(mPersonList.get(position).getContactno());
holder.tv_email.setText(mPersonList.get(position).getEmail());
holder.tv_dob.setText(mPersonList.get(position).getDatepicker());
holder.tv_qualification.setText(mPersonList.get(position).getQualification());
holder.tv_time.setText(mPersonList.get(position).getTimepicker());
return convertView;
}
#Override
public long getItemId(int position) {
return position;
}
class ViewHolder {
TextView tv_name;
TextView tv_email;
TextView tv_contactno;
TextView tv_dob;
TextView tv_qualification;
TextView tv_time;
}
}
second_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/tv_name1"
android:text="Name"
android:textSize="15dp"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/tv_phoneno"
android:layout_below="#+id/tv_name1"
android:text="contactno"
android:textSize="15dp"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/tv_phoneno"
android:id="#+id/tv_email"
android:text="Email"
android:textSize="15dp"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/tv_dob"
android:layout_below="#+id/tv_email"
android:text="DOB"
android:textSize="15dp"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/tv_qualification"
android:layout_below="#+id/tv_dob"
android:text="Qualification"
android:textSize="15dp"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/tv_time"
android:layout_below="#+id/tv_qualification"
android:text="Time"
android:textSize="15dp"
/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:layout_marginTop="120dp"
android:weightSum="2"
>
<Button
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_below="#+id/tv_time"
android:layout_weight="1"
android:textSize="15dp"
android:text="Delete"
android:padding="10dp"
android:id="#+id/delete"
android:layout_marginLeft="10dp"
/>
<Button
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textSize="15dp"
android:text="Upadate"
android:padding="10dp"
android:id="#+id/update"
android:layout_marginLeft="10dp"
/>
</LinearLayout>
</RelativeLayout>
list_view.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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=".Person">
<ListView
android:id="#+id/listView"
android:layout_width="match_parent"
android:layout_height="match_parent">
</ListView>
</RelativeLayout>
MainActivity.java
package com.example.android.persondetails;
import android.app.DatePickerDialog; import android.app.TimePickerDialog; import android.content.Intent; import android.icu.text.SimpleDateFormat; import android.os.Build; import android.support.annotation.RequiresApi; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.DatePicker; import android.widget.EditText; import android.widget.TextView; import android.widget.TimePicker;
import java.text.ParseException; import java.util.Calendar; import java.util.Date;
import static android.content.Intent.EXTRA_EMAIL; import static android.content.Intent.EXTRA_PHONE_NUMBER; import static android.os.DropBoxManager.EXTRA_TIME; import static android.security.KeyChain.EXTRA_NAME;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
public static final String EXTRA_NAME = "com.example.android.persondetails.EXTRA_NAME";
public static final String EXTRA_EMAIL = "com.example.android.persondetails.EXTRA_EMAIL";
public static final String EXTRA_PHONE_NUMBER = "com.example.android.persondetails.EXTRA_PHONE_NUMBER";
public static final String EXTRA_DOB = "com.example.android.persondetails.EXTRA_DOB";
public static final String EXTRA_QUALIFICATION = "com.example.android.persondetails.EXTRA_QUALIFICATION";
public static final String EXTRA_TIME = "com.example.android.persondetails.EXTRA_TIME";
Button button1, button2, button3;
TextView textView1, textView2, textView3, textView4, textView5, textView6;
EditText editText1, editText2, editText3, editText4;
private int mYear, mMonth, mDay, mHour, mMinute, format;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button3 = (Button) findViewById(R.id.button_save);
textView1 = (TextView) findViewById(R.id.tv_name1);
textView2 = (TextView) findViewById(R.id.tv_email);
textView3 = (TextView) findViewById(R.id.tv_phoneno);
textView4 = (TextView) findViewById(R.id.tv_dob);
textView5 = (TextView) findViewById(R.id.tv_qualification);
textView6 = (TextView) findViewById(R.id.tv_time);
button1 = (Button) findViewById(R.id.datepicker1);
button2 = (Button) findViewById(R.id.timepicker1);
button1.setOnClickListener(this);
button2.setOnClickListener(this);
button3.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if (v == button1) {
final Calendar c = Calendar.getInstance();
mYear = c.get(Calendar.YEAR);
mMonth = c.get(Calendar.MONTH);
mDay = c.get(Calendar.DAY_OF_MONTH);
format = c.get(Calendar.AM_PM);
DatePickerDialog datePickerDialog = new DatePickerDialog(this,
new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year,
int monthOfYear, int dayOfMonth) {
textView4.setText(dayOfMonth + "-" + (monthOfYear + 1) + "-" + year);
}
}, mYear, mMonth, mDay);
datePickerDialog.show();
}
if (v == button2) {
final Calendar c = Calendar.getInstance();
mHour = c.get(Calendar.HOUR_OF_DAY);
mMinute = c.get(Calendar.MINUTE);
format = c.get(Calendar.AM_PM);
final TimePickerDialog timePickerDialog;
timePickerDialog = new TimePickerDialog(this,
new TimePickerDialog.OnTimeSetListener() {
#RequiresApi(api = Build.VERSION_CODES.N)
#Override
public void onTimeSet(TimePicker timePicker, int selectedHour, int selectedMinute) {
String time = selectedHour + ":" + selectedMinute;
SimpleDateFormat fmt = new SimpleDateFormat("HH:mm");
Date date = null;
try {
date = fmt.parse(time);
} catch (ParseException e) {
e.printStackTrace();
}
SimpleDateFormat fmtOut = new SimpleDateFormat("hh:mm aa");
String formattedTime = fmtOut.format(date);
textView6.setText(formattedTime);
}
}, mHour, mMinute, false);
timePickerDialog.setTitle("Select Time");
timePickerDialog.show();
}
if (v == button3) {
EditText editText1 = (EditText) findViewById(R.id.et_name1);
String text = editText1.getText().toString();
EditText editText2 = (EditText) findViewById(R.id.et_email);
String text1 = editText2.getText().toString();
EditText editText3 = (EditText) findViewById(R.id.et_phoneno);
String number = String.valueOf(editText3.getText().toString());
Button button1 = (Button) findViewById(R.id.datepicker1);
String number1 = button1.getText().toString();
EditText editText4 = (EditText) findViewById(R.id.et_qualification);
String text2 = editText4.getText().toString();
Button button2 = (Button) findViewById(R.id.timepicker1);
String number2 = button2.getText().toString();
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
intent.putExtra(EXTRA_NAME, text);
intent.putExtra(EXTRA_EMAIL, text1);
intent.putExtra(EXTRA_PHONE_NUMBER, number);
intent.putExtra(EXTRA_DOB, number1);
intent.putExtra(EXTRA_QUALIFICATION, text2);
intent.putExtra(EXTRA_TIME, number2);
startActivity(intent);
}
}
}
I have noticed one major issue as mentioned below in comment.
public class SecondActivity extends AppCompatActivity {
private ListView lvContact;
private Button addBtn,dleBtn;
private PersonListAdapter adapter;
private List<Person> mPersonList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second_layout);
//Error as creating a new object mPersonList which is local to onCreate()
//Finally class variable mPersonList will be null still.
//ArrayList<Person> mPersonList = new ArrayList<Person>(); //Logical Error
//Solution: Use class variable instead of creating a new variable. So, just replace the above commented line with below one.
mPersonList = new ArrayList<Person>();
addBtn = (Button) findViewById(R.id.update);
..... continue
}
Hope it will solve your issue.
My Android app is composed of an SQLite database which populates individual ListView items with data user saves. Those items are available for display in activity_main.xml.
I have a class called RecordsListFragment which contains the two problematic methods: onItemClick and onItemLongClick. Here is the class in its entirety:
package com.example.benignfella.projectworkinghoursapplication.Fragment;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
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.ListView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import com.example.benignfella.projectworkinghoursapplication.R;
import com.example.benignfella.projectworkinghoursapplication.Adapter.RecordsListAdapter;
import com.example.benignfella.projectworkinghoursapplication.Database.RecordsDAO;
import com.example.benignfella.projectworkinghoursapplication.GetSet.Records;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
public class RecordsListFragment extends Fragment implements OnItemClickListener, OnItemLongClickListener {
public static final String ARGUMENT_ITEM_ID = "records_list";
Activity activity;
ListView recordsListView;
ArrayList<Records> records;
RecordsListAdapter recordsListAdapter;
RecordsDAO recordsDAO;
private GetRecordsTask task;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
activity = getActivity();
recordsDAO = new RecordsDAO(activity);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_records_list, container, false);
findViewsById(view);
task = new GetRecordsTask(activity);
task.execute((Void) null);
return view;
}
private void findViewsById(View view) {
recordsListView = (ListView) view.findViewById(R.id.list_records);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Records record = (Records) parent.getItemAtPosition(position);
if (records != null) {
Bundle arguments = new Bundle();
arguments.putParcelable("selectedRecord,", record);
CustomRecordsDialogFragment customRecordsDialogFragment = new CustomRecordsDialogFragment();
customRecordsDialogFragment.setArguments(arguments);
customRecordsDialogFragment.show(getFragmentManager(), CustomRecordsDialogFragment.ARGUMENT_ITEM_ID);
}
}
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
Records records = (Records) parent.getItemAtPosition(position);
recordsDAO.deleteRecord(records);
recordsListAdapter.remove(records);
return true;
}
public class GetRecordsTask extends AsyncTask<Void, Void, ArrayList<Records>> {
private final WeakReference<Activity> activityWeakRef;
public GetRecordsTask(Activity context) {
this.activityWeakRef = new WeakReference<Activity>(context);
}
#Override
protected ArrayList<Records> doInBackground(Void... arg0) {
ArrayList<Records> recordsArrayList = recordsDAO.getRecords();
return recordsArrayList;
}
#Override
protected void onPostExecute(ArrayList<Records> empList) {
if (activityWeakRef.get() != null && !activityWeakRef.get().isFinishing()) {
records = empList;
if (empList != null) {
if (empList.size() != 0) {
recordsListAdapter = new RecordsListAdapter(activity, empList);
recordsListView.setAdapter(recordsListAdapter);
} else {
Toast.makeText(activity, "No Records about records... wait wot m8?",
Toast.LENGTH_LONG).show();
}
}
}
}
}
public void updateView() {
task = new GetRecordsTask(activity);
task.execute((Void) null);
}
public void onResume() {
getActivity().setTitle(R.string.app_name);
getActivity().getActionBar().setTitle(R.string.app_name);
super.onResume();
}
}
Here is activity_main.xml with FrameLayout:
<RelativeLayout
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=".MainActivity">
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>
Layout resource file which contains a ListView is called fragment_records_list.xml and here it is:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#f9f9f9">
<ListView
android:id="#+id/list_records"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:dividerHeight="10dp"
android:drawSelectorOnTop="true"
android:footerDividersEnabled="false"
android:padding="10dp"
android:scrollbarStyle="outsideOverlay"/>
</RelativeLayout>
Lastly, there is a resource file containing the layout of a single item, list_item.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ededed"
android:descendantFocusability="blocksDescendants">
<RelativeLayout
android:id="#+id/layout_item"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/text_record_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="5dp"
android:text="ID"
android:textSize="20dp"/>
<TextView
android:id="#+id/text_record_date"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/text_record_id"
android:padding="5dp"
android:text="Date"
android:textColor="#00942b"
android:textSize="20dp"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/text_record_date"
android:drawableStart="#drawable/ic_date_range_black_24dp"
android:padding="5dp"
/>
<TextView
android:id="#+id/text_record_description"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/text_record_id"
android:padding="5dp"
android:text="Description"
/>
<TextView
android:id="#+id/text_record_start"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/text_record_description"
android:padding="5dp"
android:text="17:00"
android:textSize="16dp"
android:textColor="#004561"
/>
<TextView
android:id="#+id/text_record_dash"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/text_record_description"
android:layout_toRightOf="#id/text_record_start"
android:padding="5dp"
android:text="-"
android:textSize="16dp"
/>
<TextView
android:id="#+id/text_record_finish"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/text_record_description"
android:layout_toRightOf="#id/text_record_dash"
android:padding="5dp"
android:text="20:00"
android:textSize="16dp"
android:textColor="#c7002a"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="5dp"
android:layout_below="#id/text_record_description"
android:layout_toRightOf="#id/text_record_finish"
android:drawableStart="#drawable/ic_timer_black_24dp"
/>
</RelativeLayout>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_below="#id/layout_item"
android:background="#000000"
/>
</RelativeLayout>
I haven't found a definite answer to my question, so I'm asking for a bit of help here.
You need set OnItemClickListener and OnLongItemClickListener to ListView, I edited your method in the initializing variable ListView:
private void findViewsById(View view) {
recordsListView = (ListView) view.findViewById(R.id.list_records);
recordsListView.setOnItemClickListener(this);
recordsListView.setOnItemLongClickListener(this);
}
good evening dear friends, I'm working with SQLite db and android android applications I have a problem with my button when I click on login activity the message "could not execute for android onClick" my code are:
for LoginDatabaseAdapter.java class:
package com.delaroystudios.bus_seat_booking_system;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
/**
* Created by mugenzi israel on 9/19/2017.
*/
public class LoginDataBaseAdapter {
static final String DATABASE_NAME = "login.db";
static final int DATABASE_VERSION = 1;
static final String TABLE_NAME ="LOGIN";
public static final int NAME_COLUMN = 1;
static final String DATABASE_CREATE = "CREATE TABLE" + TABLE_NAME + "(" + " ID " + " INTEGER PRIMARY KEY AUTOINCREMENT," + " USERNAME text, PASSWORD text );";
public SQLiteDatabase db;
private Context context ;
private DataBaseHelper dbHelper;
public LoginDataBaseAdapter(Context _context){
Context context;
context = _context;
dbHelper = new DataBaseHelper(context,DATABASE_NAME,null,DATABASE_VERSION);
}
public LoginDataBaseAdapter open() throws SQLException{
db = dbHelper.getWritableDatabase();
return this;
}
public void close(){
db.close();
}
public SQLiteDatabase getDatabaseInstance(){
return db;
}
public void insertEntry(String userName,String password){
ContentValues newValues = new ContentValues();
newValues.put("USERNAME",userName);
newValues.put("PASSWORD",password);
db.insert("LOGIN",null,newValues);
}
public int deleteEntry(String UserName){
String where = "USERNAME=?";
int numberOFEntriesDeleted;
numberOFEntriesDeleted = db.delete(
"LOGIN",where, new String[]{
UserName}
);
return numberOFEntriesDeleted;
}
public String getSingleEntry(String userName){
Cursor cursor = db.query("LOGIN",null,"USERNAME=?",new String[]{userName},null,null,null);
if(cursor.getCount()<1){
cursor.close();
return "NOT EXIST";
}
cursor.moveToFirst();
String password = cursor.getString(cursor.getColumnIndex("PASSWORD"));
cursor.close();
return password;
}
public void updateEntry(String userName,String password){
ContentValues updatedValues = new ContentValues();
updatedValues.put("USERNAME",userName);
updatedValues.put("PASSWORD",password);
String where = "USERNAME = ?";
db.update("LOGIN",updatedValues,where,new String[]{userName});
}
}
code for DatabaseHelper.java class:
package com.delaroystudios.bus_seat_booking_system;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
/**
* Created by mugenzi israel on 9/19/2017.
*/
public class DataBaseHelper extends SQLiteOpenHelper {
public DataBaseHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version){
super(context,name,factory,version);
}
private static final String TABLE_NAME = "LOGIN";
static final String DATABASE_CREATE = "CREATE TABLE" + TABLE_NAME + "(" + " ID " + " INTEGER PRIMARY KEY AUTOINCREMENT," + " USERNAME text, PASSWORD text );";
#Override
public void onCreate(SQLiteDatabase _db){
_db.execSQL(LoginDataBaseAdapter.DATABASE_CREATE);
}
#Override
public void onUpgrade(SQLiteDatabase _db,int _oldVersion,int _newVersion){
Log.w("TaskDBAdapter","Upgrading from version"+_oldVersion+"to"+_newVersion+
",which will destroy all old data") ;
_db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(_db);
}
}
code for Main_activity_login.java class:
package com.delaroystudios.bus_seat_booking_system;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.SpinnerAdapter;
import android.widget.TextView;
import android.widget.Toast;
public class Main_activity_login extends AppCompatActivity {
Button login;
Button sign;
LoginDataBaseAdapter loginDataBaseAdapter;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_login);
/* final Button login;
final Button sign;
LoginDataBaseAdapter loginDataBaseAdapter;*/
login = (Button)findViewById(R.id.log);
final Spinner spinner = (Spinner)findViewById(R.id.spinner1);
sign = (Button)findViewById(R.id.sgn);
loginDataBaseAdapter = new LoginDataBaseAdapter(this);
loginDataBaseAdapter = loginDataBaseAdapter.open();
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,R.array.roles_selection,android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long l) {
Toast.makeText(getBaseContext(),parent.getItemAtPosition(position)+ "Selected",Toast.LENGTH_LONG).show();
((TextView) parent.getChildAt(0)).setTextColor(Color.RED);//TO change the color of spinner items
final Intent intent;
switch (position)
{
case 1:
intent = new Intent(Main_activity_login.this,Bus_info_admin.class);
startActivity(intent);
break;
case 2:
intent = new Intent(Main_activity_login.this,pick_ticket.class);
startActivity(intent);
break;
case 3:
intent = new Intent(Main_activity_login.this,SignIn.class);
startActivity(intent);
break;
case 4:
intent = new Intent(Main_activity_login.this,View_Booking.class);
startActivity(intent);
default:
System.out.println("wrong");
}
}
#Override
public void onNothingSelected(AdapterView<?> parent){
}
});
/* login.setOnClickListener(
new View.OnClickListener(){
#Override
public void onClick(View v) {
// code for button one click
Intent intent = new Intent(Main_activity_login.this,DetailsLogin.class); startActivity(intent);
}
}
);*/
sign.setOnClickListener(
new View.OnClickListener(){
#Override
public void onClick(View view){
Intent intent = new Intent(Main_activity_login.this,SignIn.class);
startActivity(intent);
}
}
);
}
public void logIn(View v){
final Dialog dialog = new Dialog(Main_activity_login.this);
dialog.setContentView(R.layout.activity_main_login);//
dialog.setTitle("Login");
final EditText editUserName = (EditText)findViewById(R.id.EditLog);
final EditText editPassword = (EditText)findViewById(R.id.Edit_menu2);
Button btnLogin = (Button)findViewById(R.id.log);
final String userName,password,storedPassword;
userName = editUserName.getText().toString();
password = editPassword.getText().toString();
storedPassword = loginDataBaseAdapter.getSingleEntry(userName);
btnLogin.setOnClickListener(
new View.OnClickListener(){
public void onClick(View v){
if (password.equals(storedPassword)){
Toast.makeText(Main_activity_login.this,"You made it!,Login successful",Toast.LENGTH_LONG).show();
dialog.dismiss();
Intent intent = new Intent(Main_activity_login.this,DetailsLogin.class);
startActivity(intent);
}
else {
Toast.makeText(Main_activity_login.this,"User name or password does not match",Toast.LENGTH_LONG).show();
}
}
}
);
}
#Override
protected void onDestroy(){
super.onDestroy();
loginDataBaseAdapter.close();
}
/*public void startActivity() {
Intent intent = new Intent(Main_activity_login.this,Bus_info_admin.class);
startActivity(intent);
}*/
/*public void buttonLoginClick(View v){
Intent intent = new Intent(v.getContext(),DetailsLogin.class);
v.getContext().startActivity(intent);
}
*/
}
code for SignIn.java:
package com.delaroystudios.bus_seat_booking_system;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class SignIn extends AppCompatActivity { //AppCompatActivity
EditText editUserName,editPassword,editConfirmPassword;
Button btnCreateAccount,btn;
Context context = this;
LoginDataBaseAdapter loginDataBaseAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_in);
loginDataBaseAdapter = new LoginDataBaseAdapter(this);
loginDataBaseAdapter = loginDataBaseAdapter.open();
editUserName =(EditText)findViewById(R.id.id_name);
editPassword = (EditText)findViewById(R.id.email);
editConfirmPassword = (EditText)findViewById(R.id.password);
btnCreateAccount = (Button)findViewById(R.id.register) ;
btnCreateAccount.setOnClickListener(
new View.OnClickListener(){
public void onClick(View v){
String userName = editUserName.getText().toString();
String password = editPassword.getText().toString();
String confirmPassword = editConfirmPassword.getText().toString();
if (userName.equals("")||password.equals("")||confirmPassword.equals("")){
Toast.makeText(getApplicationContext(),"Field Vacant",Toast.LENGTH_LONG).show();
return;
}
if (!password.equals(confirmPassword)){
Toast.makeText(getApplicationContext(),"Password does not match",Toast.LENGTH_LONG).show();
return;
}
else {
loginDataBaseAdapter.insertEntry(userName,password);
Toast.makeText(getApplicationContext(),"Account Successfully created",Toast.LENGTH_LONG).show();
Intent i = new Intent(SignIn.this,Main_activity_login.class);
startActivity(i);
finish();
}
}
}
);
/*btn.setOnClickListener(
new View.OnClickListener(){
#Override
public void onClick(View view){
Intent intent = new Intent(SignIn.this,Main_activity_login.class);
startActivity(intent);
}
);*/
}
#Override
protected void onDestroy(){
super.onDestroy();
loginDataBaseAdapter.close();
}
}
code for sign_in.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
android:orientation="vertical"
tools:context="com.delaroystudios.bus_seat_booking_system.SignIn">
<TextView
android:layout_width="match_parent"
android:layout_height="50dp"
android:text="#string/register_here"
android:textSize="32sp"
android:gravity="center"
android:layout_marginTop="30dp"
/>
<EditText
android:layout_marginTop="40dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/user_id"
android:id="#+id/id_user"
/>
<EditText
android:layout_marginTop="30dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/full_name"
android:id="#+id/id_name"
/>
<EditText
android:layout_marginTop="30dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/phone_no"
android:id="#+id/phone"
/>
<EditText
android:id="#+id/email"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="30dp"
android:hint="#string/email_id"
/>
<EditText
android:layout_marginTop="30dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/password"
android:id="#+id/password"
android:layout_marginBottom="20dp"
/>
<Button
android:id="#+id/register"
android:layout_width="150dp"
android:layout_height="50dp"
android:layout_gravity="center"
android:text="#string/register"
android:onClick="onClick"
/>
</LinearLayout>
code for activity_main_login.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
android:orientation="horizontal"
tools:context="com.delaroystudios.bus_seat_booking_system.Main_activity_login"
android:background="#drawable/bus1"
>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:id="#+id/menu1"
android:layout_marginBottom="100dp"
android:layout_marginTop="20dp"
android:gravity="center"
android:layout_marginStart="30dp"
>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/home"
android:textSize="20sp"
android:textColor="#9b59b6"
/>
<Button
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/about"
android:textColor="#9b59b6"
android:textSize="20sp" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/contact"
android:textSize="20sp"
android:textColor="#9b59b6"
/>
<!--a verifier -->
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_below="#+id/menu1"
android:id="#+id/menu2"
android:layout_marginBottom="30dp"
>
<TextView
android:layout_width="150dp"
android:layout_height="wrap_content"
android:text="#string/Login2"
android:textSize="28sp"
android:textColor="#9b59b6"
/>
<EditText
android:id="#+id/EditLog"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/login"
android:textColorHint="#9b59b6"
android:textColor="#ffffff"
/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_below="#+id/menu2"
android:id="#+id/menu3"
android:layout_marginBottom="30dp"
>
<TextView
android:id="#+id/textView"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:text="#string/Pass"
android:textSize="28sp"
android:textColor="#9b59b6"
/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/your_password"
android:id="#+id/Edit_menu2"
android:textColorHint="#9b59b6"
android:textColor="#ffffff"
/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_below="#+id/menu3"
android:layout_marginBottom="10dp"
android:id="#+id/role"
>
<TextView
android:id="#+id/T_role"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:text="#string/role"
android:textSize="28sp"
android:textColor="#9b59b6"
/>
<Spinner
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/spinner1"
/>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:id="#+id/men1"
android:layout_marginTop="70dp"
android:layout_below="#+id/role"
android:gravity="center"
android:layout_marginStart="30dp"
>
<Button
android:id="#+id/log"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_marginEnd="30dp"
android:onClick="logIn"
android:text="#string/login"
android:textColor="#9b59b6"
android:textColorHint="#9b59b6"
android:textSize="20sp"
/>
<Button
android:id="#+id/sgn"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_marginEnd="30dp"
android:onClick="onClick"
android:text="#string/sign_in"
android:textColor="#9b59b6"
android:textColorHint="#9b59b6"
android:textSize="20sp"
/>
In sign_in.xml,
<Button
android:id="#+id/register"
android:layout_width="150dp"
android:layout_height="50dp"
android:layout_gravity="center"
android:text="#string/register"
android:onClick="onClick"
/>
remove android:onClick="onClick" line. That should be work.
guys in my project i need to click the item on the list and move to next activity using bundle i need to carry some data also, but i have some issue..
Please help me to move to next activity i can't understand what is the mistake i did,when i click on the item it is not even responding..
here i just use "e_name.setText("hiiii")" for testing purpose its not working.
AT THE END I HAVE MENTIONED MY LAYOUT CODES ALSO.
if possible please send me a link to learn more about custom adapter and list view..
//Main activity.java
package com.prematix.ashok.friday_9;
import android.app.ListActivity;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
EditText e_name, e_desig, e_salary;
Button save;
String itemNames[];
String itemDescriptions[];
ListView itemsListView;
ArrayList<Item> list = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
e_name = (EditText) findViewById(R.id.ed_name);
e_desig = (EditText) findViewById(R.id.ed_desig);
e_salary = (EditText) findViewById(R.id.ed_salary);
save = (Button) findViewById(R.id.save);
itemsListView = (ListView) findViewById(R.id.mylist);
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//create adapter object
CustomListAdapter adapter = new CustomListAdapter(getApplicationContext(), generateItemsList());
//set custom adapter as adapter to our list view
itemsListView.setAdapter(adapter);
}
private ArrayList<Item> generateItemsList() {
itemNames = new String[]{e_name.getText().toString()};
itemDescriptions = new String[]{e_desig.getText().toString()};
for (int i = 0; i < itemNames.length; i++) {
list.add(new Item(itemNames[i], itemDescriptions[i]));
}
return list;
}
});
itemsListView.setOnItemClickListener(new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
e_name.setText("hiiiii");
}
});
// ListView itemsListView = (ListView)findViewById(R.id.list_view_items);
}
}
//CustommListAdapter.java
package com.prematix.ashok.friday_9;
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;
/**
* Created by ${Nagaveni} on 2017-06-09.
*/
public class CustomListAdapter extends BaseAdapter {
private Context context;
private ArrayList<Item> items;
public CustomListAdapter(Context context,ArrayList<Item> items){
this.context = context;
this.items = items;
}
#Override
public int getCount() {
return items.size();
}
#Override
public Object getItem(int i) {
return items.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
if(view == null) {
view = LayoutInflater.from(context).inflate(R.layout.layout_list_view_row_items, viewGroup, false);
}
//get current item to be displayed
Item currentitem = (Item)getItem(i);
//get the text view for item name and item designation
TextView name = (TextView)view.findViewById(R.id.name);
TextView designation = (TextView)view.findViewById(R.id.desig);
TextView salary = (TextView)view.findViewById(R.id.salary);
//sets the text for item name and item designation from the current item object
name.setText(currentitem.getNames());
designation.setText(currentitem.getDesignation());
salary.setText("10,000");
//returns the view for current row
return view;
}
}
//here is my layout code
layout_list_view_items.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:layout_width="260dp"
android:layout_marginLeft="8dp"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="name"
android:id="#+id/name"
android:textStyle="bold"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="designation"
android:id="#+id/desig"
android:textStyle="bold"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="salary"
android:id="#+id/salary"
android:textStyle="bold"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_marginLeft="70dp">
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/checkBox"
android:layout_weight="1" />
</LinearLayout>
</LinearLayout>
//activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.prematix.ashok.friday_9.MainActivity">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:hint="Name"
android:ems="10"
android:id="#+id/ed_name" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:hint="Designation"
android:ems="10"
android:id="#+id/ed_desig" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:hint="Salary"
android:ems="10"
android:id="#+id/ed_salary" />
<Button
android:text="Save"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/save" />
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/mylist"/>
</LinearLayout>
I have this activity with EditViews and button. When the button is pressed I move on to a new activity. the problem is when the back button is pressed. The EditViews are not visible. What is expected is that the views and the text that was entered are visible. Also The buttons that appear are from the second activity and not the first.
<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" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context="com.ammar.android.dailyjobsiteinspection2.MainActivity1Activity">
<ScrollView
android:layout_width="fill_parent"
android:layout_height="350dp"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:id="#+id/scrollView">
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:id="#+id/linearLayout">
<TextView
android:layout_width="fill_parent"
android:layout_height="0dp"
android:text="New Text"
android:id="#+id/textView"
android:layout_gravity="center_horizontal"
android:layout_weight="1"
android:visibility="invisible" />
<EditText
android:layout_width="fill_parent"
android:layout_height="70dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:id="#+id/editText"
android:layout_gravity="center"
android:hint="Inspector ID"
/>
<TextView
android:layout_width="fill_parent"
android:layout_height="0dp"
android:text="New Text"
android:id="#+id/textView2"
android:layout_gravity="center_horizontal"
android:layout_weight="1"
android:visibility="invisible" />
<EditText
android:layout_width="fill_parent"
android:layout_height="70dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:id="#+id/editText2"
android:layout_gravity="center"
android:hint="Site Name" />
<TextView
android:layout_width="fill_parent"
android:layout_height="0dp"
android:text="New Text"
android:id="#+id/textView3"
android:layout_gravity="center_horizontal"
android:visibility="invisible"
android:layout_weight="1" />
<EditText
android:layout_width="fill_parent"
android:layout_height="70dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:id="#+id/editText3"
android:layout_gravity="center"
android:hint="Site Address" />
<Button
android:layout_width="160dp"
android:layout_height="60dp"
android:text="Start"
android:id="#+id/button3"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_gravity="center_horizontal"
android:onClick="start"
android:layout_margin="5dp" />
</LinearLayout>
</ScrollView>
</RelativeLayout>
Here is the Java code:
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
public class MainActivity1Activity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_activity1);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main_activity1, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void start(View view){
EditText editText1 = (EditText) findViewById(R.id.editText);
EditText editText2 = (EditText) findViewById(R.id.editText2);
EditText editText3 = (EditText) findViewById(R.id.editText3);
if(!allFieldsEntered(editText1, editText2, editText3)){
com.ammar.android.dailyjobsiteinspection2.Message.message(this, "All fields must be filled before starting an Audit ");
}else{
Intent intent = new Intent(this, MainActivity11Activity.class);
Bundle bundle = getDataBundle(editText1, editText2, editText3);
intent.putExtras(bundle);
setContentView(R.layout.activity_main_activity11);
startActivity(intent);
}
}
private Bundle getDataBundle(EditText editText1, EditText editText2, EditText editText3) {
Bundle bundle = new Bundle();
bundle.putString(MainActivity.INSPECTORID, editText1.getText().toString());
bundle.putString(MainActivity.SITENAME, editText2.getText().toString());
bundle.putString(MainActivity.SITEADDRESS, editText3.getText().toString());
return bundle;
}
private boolean allFieldsEntered(EditText editText1, EditText editText2, EditText editText3) {
return !(editText1.getText().toString().matches("")
|| editText2.getText().toString().matches("")
|| editText3.getText().toString().matches(""));
}
}
Here is the second activity:
<LinearLayout 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" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
android:orientation="vertical"
tools:context="com.ammar.android.dailyjobsiteinspection2.MainActivity11Activity">
<ScrollView
android:layout_width="match_parent"
android:layout_height="0dp"
android:id="#+id/scrollView"
android:layout_gravity="center_horizontal"
android:layout_weight="1">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/layout"></LinearLayout>
</ScrollView>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="60dp"
android:id="#+id/layout2">
android:layout_gravity="center_horizontal">
<TextView
android:layout_width="0dp"
android:layout_height="fill_parent"
android:text="New Text"
android:id="#+id/textView4"
android:layout_weight="1"
android:visibility="invisible" />
<Button
android:layout_width="160dp"
android:layout_height="fill_parent"
android:text="Save"
android:id="#+id/button4"
android:onClick="save" />
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="New Text"
android:id="#+id/textView5"
android:layout_weight="1"
android:visibility="invisible"/>
<Button
android:layout_width="160dp"
android:layout_height="fill_parent"
android:text="Submit"
android:id="#+id/button5"
android:onClick="submit" />
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="New Text"
android:id="#+id/textView6"
android:layout_weight="1"
android:visibility="invisible"/>
</LinearLayout>
</LinearLayout>
and the Java code:
import android.app.ActionBar;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Typeface;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.text.Layout;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import java.util.ArrayList;
public class MainActivity11Activity extends ActionBarActivity {
private ArrayList<RadioGroup> radioGroupArrayList;
private String inspectorId;
private String siteName;
private String siteAddress;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_activity11);
setFields();
setUI();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main_activity11, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private void setFields() {
Intent intentBundle = getIntent(); // get intent
Bundle bundle = intentBundle.getExtras(); // get bundle from intent
inspectorId = bundle.getString(MainActivity.INSPECTORID);
siteName = bundle.getString(MainActivity.SITENAME);
siteAddress = bundle.getString(MainActivity.SITEADDRESS);
}
private void setUI() {
TextView textView;
radioGroupArrayList = new ArrayList<RadioGroup>();
LinearLayout ll = (LinearLayout) this.findViewById(R.id.layout);
int count = 0;
for(int i = 0; i<6; i++){
int id = getResources().getIdentifier("PreStart"+ i, "array" , getPackageName());
String [] questions = getResources().getStringArray(id);
textView = new TextView(this);
textView.setText(questions[0]);
textView.setTextSize(24);
textView.setTypeface(null, Typeface.BOLD);
ll.addView(textView);
TextView textView1;
TextView textView2;
RadioGroup radioGroup;
RadioButton radioButton1;
RadioButton radioButton2;
RadioButton radioButton3;
for (int j = 1; j< questions.length; j++){
textView1 = new TextView(this);
textView1.setText(questions[j]);
textView1.setTextSize(18);
radioGroup = new RadioGroup(this);
radioGroupArrayList.add(radioGroup);
radioButton1 = new RadioButton(this);
radioButton2 = new RadioButton(this);
radioButton3 = new RadioButton(this);
radioButton1.setText("Yes");
radioButton2.setText("No");
radioButton3.setText("NA");
radioButton1.setId(count);
radioButton2.setId(count+1);
radioButton3.setId(count+2);
count = count + 3;
radioGroup.addView(radioButton1);
radioGroup.addView(radioButton2);
radioGroup.addView(radioButton3);
radioButton1.setPadding(20, 20, 100, 20);
radioButton2.setPadding(20, 20, 100, 20);
radioButton3.setPadding(20, 20, 100, 20);
radioGroup.setOrientation(LinearLayout.HORIZONTAL);
textView2 = new TextView(this);
textView2.setVisibility(View.INVISIBLE);
ll.addView(textView1);
ll.addView(radioGroup);
ll.addView(textView2);
}
}
EditText editText = new EditText(this);
editText.setId(R.id.editText11);
editText.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.WRAP_CONTENT));
editText.setHint("Enter Comments Here");
ll.addView(editText);
}
public void save(View view){
AnswerListCreator answerCreator = new AnswerListCreator(radioGroupArrayList);
String[] answerList = answerCreator.getAnswerList();
String commentLog = ((EditText) findViewById(R.id.editText11)).getText().toString();
DBHelper dbHelper = new DBHelper(this);
SQLiteDatabase db = dbHelper.getWritableDatabase();
Site site = new Site(inspectorId, siteName, siteAddress, answerList, commentLog, 0);
dbHelper.insertSite(db, site);
// go back to main
Intent intent = new Intent(this, MainActivity.class);
setContentView(R.layout.activity_main);
startActivity(intent);
db.close();
finish();
}
public void submit(View view) {
AnswerListCreator answerCreator = new AnswerListCreator(radioGroupArrayList);
if (!answerCreator.isComplete()) {
com.ammar.android.dailyjobsiteinspection2.Message.message(this, "All fields must be checked");
} else {
answerCreator = new AnswerListCreator(radioGroupArrayList);
String[] answerList = answerCreator.getAnswerList();
String commentLog = ((EditText) findViewById(R.id.editText11)).getText().toString();
DBHelper dbHelper = new DBHelper(this);
SQLiteDatabase db = dbHelper.getWritableDatabase();
Site site = new Site(inspectorId, siteName, siteAddress, answerList, commentLog, 1);
dbHelper.insertSite(db, site);
// go back to main
Intent intent = new Intent(this, MainActivity.class);
setContentView(R.layout.activity_main);
startActivity(intent);
db.close();
finish();
}
}
}
You are changing first Activity's View before calling StartActivity.
Remove this in MainActivity1Activity:
setContentView(R.layout.activity_main_activity11);
Furthermore, if you want to keep view state in MainActivity1Activity don't start it again. Just call finish() in second activity.