Android: time picker in a dialog - java

I tried to modify this time picker I found here on stackoverflow and placed it in a dialog in my application. When I try to pick the time the result is not what I setted but it is the time of the device, so the time isn't set well. The function TimeSetting is used to call the time picker. I tryed to make it start from zero and take the right time but with no result. Can someone help me find out where the error is?
here is the ExampleDialog.java file:
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatDialogFragment;
import com.ikovac.timepickerwithseconds.MyTimePickerDialog;
import com.ikovac.timepickerwithseconds.TimePicker;
import java.util.Calendar;
public class ExampleDialog extends AppCompatDialogFragment {
private EditText textInputNome;
private ExampleDialogListener listener;
private Button positiveButton;
private TextView text_view_timesec;
private Button SetTimeBTN;
private String nome = null;
private int timeInSeconds=-1;
private int hourOfDay;
private int minute;
private int seconds;
/*for MainActivity*/
public interface ExampleDialogListener {
boolean applyProgram(String nome);
}
#NonNull
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
final LayoutInflater inflater = getActivity().getLayoutInflater();
View view = inflater.inflate(R.layout.layout_dialog, null);
textInputNome = view.findViewById(R.id.tiCrea);
SetTimeBTN=view.findViewById(R.id.btn_SetTime);
text_view_timesec=view.findViewById(R.id.textView3);
textInputNome.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
TimeSetting();
}
#SuppressLint("SetTextI18n")
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
nome =textInputNome.getText().toString().trim();
TimeSetting();
}
#Override
public void afterTextChanged(Editable s) {
TimeSetting();
}
});
builder.setView(view);
builder.setTitle("Nome programma");
builder.setNegativeButton("delete", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
builder.setPositiveButton("create", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
String nome = textInputNome.getText().toString().trim();
listener.applyProgram(nome);
}
});
Dialog dialog = builder.create();
return dialog;
}
#Override
public void onAttach(#NonNull Context context) {
super.onAttach(context);
try {
listener = (ExampleDialogListener) context;
} catch (ClassCastException e) {
throw new ClassCastException(context.toString() +
"must implement ExampleDialogListener");
}
}
#Override
public void onDetach() {
super.onDetach();
listener = null;
}
#Override
public void onStart() {
super.onStart();
AlertDialog d = (AlertDialog) getDialog();
if (d != null ) {
positiveButton = d.getButton(Dialog.BUTTON_POSITIVE);
positiveButton.setEnabled(false);
}
}
private void TimeSetting(){
SetTimeBTN.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getContext(), "Btn clicked", Toast.LENGTH_SHORT).show();
Calendar c = Calendar.getInstance();
MyTimePickerDialog mTimePicker = new MyTimePickerDialog(getContext(), new MyTimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute, int seconds) {
SetTimeBTN.setText(getString(R.string.time) + String.format("%02d", hourOfDay) + ":" + String.format("%02d", minute) + ":" + String.format("%02d", seconds));
}
}, hourOfDay=c.get(Calendar.HOUR_OF_DAY), minute=c.get(Calendar.MINUTE), seconds=c.get(Calendar.SECOND), true);
timeInSeconds = ((hourOfDay * 60 * 60) + (minute * 60) + seconds);
text_view_timesec.setText("hh=" + hourOfDay + " mm=" + minute + " ss=" + seconds + " time tot=" + timeInSeconds);
positiveButton.setEnabled(!nome.isEmpty() && timeInSeconds > 0);
mTimePicker.show();
}
});
}
}
Here is the xml of the dialog:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/time_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp">
<com.google.android.material.textfield.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<com.google.android.material.textfield.TextInputEditText
android:id="#+id/tiCrea"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/name"
android:inputType="text" />
</com.google.android.material.textfield.TextInputLayout>
<Button
android:id="#+id/btn_SetTime"
style="#style/Widget.AppCompat.Button.Borderless"
android:layout_width="186dp"
android:layout_height="wrap_content"
android:text="#string/clickToSetTime"
android:textAlignment="viewStart"
android:gravity="start" />
<TextView
android:id="#+id/textView3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="here is the time setted from the timepkr" />
</LinearLayout>

in onCreate method change this two lines
final LayoutInflater inflater = getActivity().getLayoutInflater();
View view = inflater.inflate(R.layout.layout_dialog, null);
to
final LinearLayoutInflater inflater = getActivity().getLayoutInflater();
View view = inflater.inflate(R.layout.layout_dialog, (ViewGroup)R.id.time_view");//here the id of the root LinearLayout in the XMl File layout_dialog.

Related

How to get data from an item in a recyclerView and view it in a different activity on editTexts

When the user logins an activity where the user can create their account opens (CreateProfileActivity). When the profile is created the user is redirected to the recyclerView activity where their profile info is displayed in a recyclerView. When user clicks on the item in recyclerView the Update Activity will open. I want their profile information from the recyclerView to load on the Update Activity. Please help.
P.S. Since I haven't made the CreateProfile_Activity open only once, as I don't want the user to create more than one profile, So for now: I ran the app once and created an account and then I changed it so now when the user logins it opens the recyclerView_Activity.
Here is the recyclerView_Activity
package com.example.insert_update_activity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class recyclerView_Activity extends AppCompatActivity {
// Button insertBtn;
RecyclerView recyclerView;
DBHelper myDB;
ArrayList<String> temp_id, temp_name, temp_age;
myAdapter myAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_recycler_view);
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
/* insertBtn = (Button) findViewById(R.id.insertBtn);
insertBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(recyclerView_Activity.this, Insert_Activity.class);
startActivity(intent);
}
});*/
myDB = new DBHelper(recyclerView_Activity.this);
temp_id = new ArrayList<>();
temp_name = new ArrayList<>();
temp_age = new ArrayList<>();
storeDataInArrays();
myAdapter = new myAdapter(recyclerView_Activity.this, this, temp_id, temp_name, temp_age);
recyclerView.setAdapter(myAdapter);
recyclerView.setLayoutManager(new LinearLayoutManager(recyclerView_Activity.this));
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1)
{
recreate();
}
}
void storeDataInArrays() {
Cursor cursor = myDB.readData(); // Cursor cursor = myDB.readAllData();
if (cursor.getCount() == 0)
{
Toast.makeText(recyclerView_Activity.this, "No Data", Toast.LENGTH_SHORT).show();
}
else
{
while (cursor.moveToNext()) {
temp_id.add(cursor.getString(0));
temp_name.add(cursor.getString(1));
temp_age.add(cursor.getString(2));
}
}
}
}
Here is the UpdateActivity
package com.example.insert_update_activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
public class Update_Activity extends AppCompatActivity {
EditText name, age;
Button updateBtn;
String id;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_update);
name = (EditText) findViewById(R.id.edit_name);
age = (EditText) findViewById(R.id.edit_age);
updateBtn = (Button) findViewById(R.id.updateBtn);
updateBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String sName = name.getText().toString().trim();
String sAge = age.getText().toString().trim();
DBHelper db = new DBHelper(Update_Activity.this);
db.updateData(id, sName, sAge);
Intent intent = new Intent(Update_Activity.this, com.example.insert_update_activity.recyclerView_Activity.class);
startActivity(intent);
}
});
getAndSetIntentData();
}
void getAndSetIntentData() {
if (getIntent().hasExtra("id") && getIntent().hasExtra("Name") && getIntent().hasExtra("Age"))
{
// Getting data from Intent
id = getIntent().getStringExtra("id");
String NAME = getIntent().getStringExtra("Name");
String AGE = getIntent().getStringExtra("Age");
// Setting Intent Data
name.setText(NAME);
age.setText(AGE);
}
else
{
Toast.makeText(Update_Activity.this, "No Data", Toast.LENGTH_SHORT).show();
}
}
}
Here is the DBHelper
package com.example.insert_update_activity;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.widget.Toast;
import androidx.annotation.Nullable;
public class DBHelper extends SQLiteOpenHelper {
private Context context;
private static final String DATABASE_NAME = "Database.db";
private static final int DATABASE_VERSION = 1;
// Create table
private static final String TABLE_TEMP = "TEMPP";
private static final String COLUMN_ID = "id";
private static final String COLUMN_NAME = "name";
private static final String COLUMN_AGE = "age";
public DBHelper(#Nullable Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
this.context = context;
}
#Override
public void onCreate(SQLiteDatabase db) {
String profileQuery = "CREATE TABLE " + TABLE_TEMP +
" (" + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COLUMN_NAME + " TEXT, " + COLUMN_AGE + " INTEGER " + ")";
db.execSQL(profileQuery);
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_TEMP);
onCreate(db);
}
// Functions for TEMP TABLE ******************************************************************************************************************************************** PROFILE TEMP
public Boolean insertData(String name, String age) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(COLUMN_NAME, name);
cv.put(COLUMN_AGE, age);
long result = db.insert(TABLE_TEMP, null, cv);
if (result == -1) {
Toast.makeText(context, "Failed to Insert", Toast.LENGTH_SHORT).show();
return false;
} else {
Toast.makeText(context, "Data Inserted Successfully!", Toast.LENGTH_SHORT).show();
return true;
}
}
Cursor readData() {
String query = "SELECT * FROM " + TABLE_TEMP;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = null;
if (db != null) {
cursor = db.rawQuery(query, null);
}
return cursor;
}
// Update data using where clause;
public Boolean updateData(String row_id, String name, String age)
{
SQLiteDatabase db = this.getWritableDatabase(); // SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(COLUMN_NAME, name);
cv.put(COLUMN_AGE, age);
long result = db.update(TABLE_TEMP, cv, COLUMN_ID + " =? ", new String[]{row_id});
if (result == -1)
{
Toast.makeText(context, "Failed to Update", Toast.LENGTH_SHORT).show();
return false;
}
else
{
Toast.makeText(context, "Successfully Updated!", Toast.LENGTH_SHORT).show();
return true;
}
}
}
Here is the Adapter
package com.example.insert_update_activity;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class myAdapter extends RecyclerView.Adapter<myAdapter.MyViewHolder> {
private Context context;
Activity activity;
private ArrayList id, name, age;
myAdapter(Activity activity, Context context, ArrayList id, ArrayList name, ArrayList age) {
this.activity = activity;
this.context = context;
this.id = id;
this.name = name;
this.age = age;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.my_row, parent, false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, final int position) {
holder.id_txt.setText(String.valueOf(id.get(position)));
holder.name_txt.setText(String.valueOf(name.get(position)));
holder.age_txt.setText(String.valueOf(age.get(position)));
holder.mainLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, Update_Activity.class);
intent.putExtra("id", String.valueOf(id.get(position)));
intent.putExtra("name", String.valueOf(name.get(position)));
intent.putExtra("age", String.valueOf(age.get(position)));
activity.startActivityForResult(intent, 1);
}
});
}
#Override
public int getItemCount() {
return id.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView id_txt, name_txt, age_txt;
LinearLayout mainLayout;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
id_txt = itemView.findViewById(R.id.id_txt);
name_txt = itemView.findViewById(R.id.name_txt);
age_txt = itemView.findViewById(R.id.age_txt);
mainLayout = itemView.findViewById(R.id.mainLayout);
}
}
}
And here is the xml file my_row for the recyclerView
<?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="wrap_content"
android:orientation="vertical"
android:id="#+id/mainLayout">
<androidx.cardview.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:outlineSpotShadowColor="#000000"
app:cardElevation="3dp">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="12dp">
<TextView
android:id="#+id/id_txt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="10dp"
android:text="1"
android:textColor="#9A9797"
android:textSize="35dp"
android:textStyle="bold"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/nameTitle"
android:layout_width="90dp"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:text="NAME:"
android:textColor="#000"
android:textSize="16sp"
android:textStyle="bold"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/ageTitle"
android:layout_width="90dp"
android:layout_height="wrap_content"
android:text="AGE:"
android:textColor="#000"
android:textSize="16sp"
android:textStyle="bold"
app:layout_constraintStart_toStartOf="#+id/nameTitle"
app:layout_constraintTop_toBottomOf="#+id/nameTitle" />
<TextView
android:id="#+id/name_txt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Name"
android:textSize="15sp"
app:layout_constraintStart_toEndOf="#+id/nameTitle"
app:layout_constraintTop_toTopOf="#+id/nameTitle" />
<TextView
android:id="#+id/age_txt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Age"
android:textSize="15sp"
app:layout_constraintStart_toEndOf="#+id/ageTitle"
app:layout_constraintTop_toBottomOf="#+id/nameTitle" />
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.cardview.widget.CardView>
</LinearLayout>
The login activity is pretty simple. It just allows the user to login if username == "User1" and password == "123456".
The CreateProfile_Activity just uses the insertData once
Okay so now it works. I'm not sure this is why, but I will post the changes I made.
So one problem was in myAdapter. In the mainLayout OnClick the "name" and "age" where different from the "Name" and "Age" in the UpdateActivity where I get data from Intent. The first letters of both 'age' and 'name' were not in CAPITALS.
Another thing I changed was the get(position) in the onBindHolder.
Now the onBindHolder looks like this:
public void onBindViewHolder(#NonNull MyViewHolder holder, final int position) {
holder.id_txt.setText(String.valueOf(id.get(holder.getAdapterPosition())));
holder.name_txt.setText(String.valueOf(name.get(holder.getAdapterPosition())));
holder.age_txt.setText(String.valueOf(age.get(holder.getAdapterPosition())));
holder.mainLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext(), Update_Activity.class);
intent.putExtra("id", String.valueOf(id.get(holder.getAdapterPosition())));
intent.putExtra("Name", String.valueOf(name.get(holder.getAdapterPosition())));
intent.putExtra("Age", String.valueOf(age.get(holder.getAdapterPosition())));
v.getContext().startActivity(intent);
//activity.startActivityForResult(intent, 1);
}
});
}
Hope it helps anyone

Date picker from SwipeStackAdapter adapter

I have googled alot. But i did't get the solution.
My issue is i have one fragment. In the fragment i am inflating some cards ie the swipe cards. for that swipe cards layout im using SwipeStackAdapter to inflate the view xml.
The in one of my xml view im trying to implement the datepicker.
TaskCardListShow.java fragment code
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.BaseAdapter;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import android.support.v7.app.AppCompatActivity;
import com.jmedeisis.draglinearlayout.DragLinearLayout;
import java.util.ArrayList;
import java.util.List;
import link.fls.swipestack.SwipeStack;
public class TaskCardListShow extends Fragment implements SwipeStack.SwipeStackListener, View.OnClickListener {
private ArrayList<String> mData;
private ArrayList<String> LayOutData;
private SwipeStack mSwipeStack;
private SwipeStackAdapter mAdapter;
public int cardCounter;
Context context;
AutoCompleteTextView autoTextView;
public TaskCardListShow() {
}
public static TaskCardListShow newInstance() {
TaskCardListShow _TaskCardListShow = new TaskCardListShow();
return _TaskCardListShow;
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.task_card_list_show, container, false);
mSwipeStack = (SwipeStack) view.findViewById(R.id.swipeStack);
mData = new ArrayList<>();
LayOutData = new ArrayList<>();
mAdapter = new SwipeStackAdapter(mData,LayOutData);
mSwipeStack.setAdapter(mAdapter);
mSwipeStack.setListener(this);
context=getActivity().getApplicationContext();
cardCounter=7;// write function for getting card count.
fillStackCard();
return view;
}
private void fillStackCard() {
for (int x = 0; x <cardCounter; x++) {
mData.add(getString(R.string.dummy_text) + " " + (x + 1));
LayOutData.add(getString(R.string.str_card)+ (x + 1));
}
}
#Override
public void onClick(View v) {
}
#Override
public void onViewSwipedToRight(int position) {
String swipedElement = mAdapter.getItem(position);
}
#Override
public void onViewSwipedToLeft(int position) {
String swipedElement = mAdapter.getItem(position);
}
#Override
public void onStackEmpty() {
removeTaskCardFragment();
}
public void removeTaskCardFragment(){
FragmentManager manager = getActivity().getSupportFragmentManager();
FragmentTransaction mFragmentTransaction = manager.beginTransaction();
TaskCardListShow _TaskCardListShowFragment = new TaskCardListShow();
mFragmentTransaction.remove(_TaskCardListShowFragment);
mFragmentTransaction.commit();
manager.popBackStack();
}
public class SwipeStackAdapter extends BaseAdapter {
private List<String> mData;
private List<String> LayOutData;
DragLinearLayout dragDropAndroidLinearLayout;
public SwipeStackAdapter(List<String> data,List<String> Ldata) {
this.mData = data;
this.LayOutData = Ldata;
}
#Override
public int getCount() {
return mData.size();
}
#Override
public String getItem(int position) {
return mData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
String LName=LayOutData.get(position);
try {
int id = getActivity().getApplicationContext().getResources().
getIdentifier(LName, "layout", getActivity().getPackageName());
convertView = getActivity().getLayoutInflater().inflate(id, parent, false);
if(position==4){ // my date picker layout will come this postion.
}
} catch (Exception e) {
e.printStackTrace();
}
return convertView;
}
}
card_4.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_height="match_parent"
android:layout_width="match_parent"
card_view:cardCornerRadius="#dimen/card_corner_radius"
card_view:cardElevation="#dimen/elevation_large"
>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:gravity="center"
android:id="#+id/TxtQuestion">
<TextView
android:id="#+id/textViewCard"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:gravity="top"
android:textColor="#color/colorAccent"
android:textStyle="bold|italic"
android:textSize="20sp"
android:padding="30dp"
android:layout_gravity="top|center_horizontal|center_vertical"
android:text="Date picker template"/>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_below="#+id/TxtQuestion"
android:layout_centerInParent="true"
android:id="#+id/linearLayout">
<DatePicker
android:id="#+id/dpResult"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
</RelativeLayout>
</android.support.v7.widget.CardView>
Can you please guide me to do this. I have tried lots of method but it is not working i my case
I have solved my problem by,
in my adapter
final TextView _dpResult=(TextView)convertView.findViewById(R.id.dpResult);
_dpResult.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
DialogFragment newFragment = new SelectDateFragment( );
newFragment.show(getFragmentManager(), "DatePicker");
}
});
SelectDateFragment
public class SelectDateFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener {
#RequiresApi(api = Build.VERSION_CODES.N)
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final Calendar calendar = Calendar.getInstance();
int yy = calendar.get(Calendar.YEAR);
int mm = calendar.get(Calendar.MONTH);
int dd = calendar.get(Calendar.DAY_OF_MONTH);
return new DatePickerDialog(getActivity(), this, yy, mm, dd);
}
public void onDateSet(DatePicker view, int yy, int mm, int dd) {
populateSetDate(yy, mm+1, dd);
}
public void populateSetDate(int year, int month, int day) {
TextView dpResult= (TextView)getActivity().findViewById(R.id.dpResult);
dpResult.setText(year+"-"+month+"-"+day);
}
}
The xml coding for the date picker is
<TextView
android:id="#+id/dpResult"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:hint="yyyy-mm-dd" />
Now i am able see the date-picker on my card. Thanks

TimePicker Dialog when clicking EditText

I used this question to get the timepicker when clicking on editext.
Please note that I am putting the code in a fragment.
What i've changed is the following:
Added : Context ctx; to the settime.java
On the line:
SetTime fromTime = new SetTime(chostime,this);
It is telling me : the constructor SetTime(editText, AppointFragment) is not defined.
I’ve tried to change it into :
SetTime fromTime = new SetTime(chostime,getActivity());
When trying to run the application gice me the following error
12-30 18:03:55.120: E/AndroidRuntime(1376): java.lang.NullPointerException
Here is the code :
AppointFragment.java
package com.example.appointapp;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.DatePicker;
import android.widget.EditText;
public class AppointFragment extends Fragment{
private static final String TAG = "AppoinFragment";
EditText chosdate, chostime;
private Appointment mappointment;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mappointment= new Appointment();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState){
View v = inflater.inflate(R.layout.fragment_appoint, parent, false);
chosdate = (EditText)v.findViewById(R.id.datea_text);
chostime = (EditText)v.findViewById(R.id.timea_text);
SetTime fromTime = new SetTime(chostime,this);
chosdate.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
DialogFragment datePickerFragment = new DatePickerFragment() {
#Override
public void onDateSet(DatePicker view, int year, int month, int day) {
Log.d(TAG, "onDateSet");
Calendar c = Calendar.getInstance();
c.set(year, month, day);
String myFormat = "dd/MM/yy";
SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.US);
chosdate.setText(sdf.format(c.getTime()));
chosdate.requestFocus();
}
};
datePickerFragment.show(getActivity().getSupportFragmentManager(), "datePicker");
}
}
});
return v;
}
}
SetTime.java
package com.example.appointapp;
import java.util.Calendar;
import android.app.TimePickerDialog;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.content.Context;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.widget.EditText;
import android.widget.TimePicker;
class SetTime implements OnFocusChangeListener, OnTimeSetListener {
private EditText editText;
private Calendar myCalendar;
Context ctx;
public SetTime(EditText editText, Context ctx){
this.editText = editText;
this.editText.setOnFocusChangeListener(this);
this.myCalendar = Calendar.getInstance();
}
#Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
int hour = myCalendar.get(Calendar.HOUR_OF_DAY);
int minute = myCalendar.get(Calendar.MINUTE);
new TimePickerDialog(ctx, this, hour, minute, true).show();
}
}
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
this.editText.setText( hourOfDay + ":" + minute);
}
}
First override onActivityCreated() in AppointFragment and then use the getActivity() to create SetTime object.
private SetTime fromTime;
private EditText chosdate, chostime;
...
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
fromTime = new SetTime(chostime,getActivity());
}
The complete code for setting the time using Fragments is below. You can use the same approach for setting the date too.
MainActivity.java
public class MainActivity extends AppCompatActivity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Create a new Fragment to be placed in the activity layout
ChildFragment firstFragment = new ChildFragment();
// In case this activity was started with special instructions from an
// Intent, pass the Intent's extras to the fragment as arguments
//firstFragment.setArguments(getIntent().getExtras());
// Add the fragment to the 'fragment_container' FrameLayout
getSupportFragmentManager().beginTransaction()
.add(R.id.frameLayout, firstFragment).commit();
}
ChildFragment.java (For displaying EditTexts)
public class ChildFragment extends Fragment implements View.OnClickListener, TimePickerFragment.Callback
{
private EditText editText;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.child_fragment, null, false);
editText = (EditText) view.findViewById(R.id.time_edit_text);
editText.setOnClickListener(this);
return view;
}
#Override
public void onClick(View view)
{
if(view == editText)
{
TimePickerFragment dialog = new TimePickerFragment();
dialog.setTargetFragment(this, 1); //request code
dialog.show(getFragmentManager(),"dialog");
}
}
#Override
public void onTimeSelected(String time)
{
editText.setText(time);
}
}
TimePickerFragment.java
public class TimePickerFragment extends DialogFragment
implements TimePickerDialog.OnTimeSetListener {
public interface Callback
{
public void onTimeSelected(String time);
}
private Callback timeCallback;
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current time as the default values for the picker
final Calendar c = Calendar.getInstance();
int hour = c.get(Calendar.HOUR_OF_DAY);
int minute = c.get(Calendar.MINUTE);
timeCallback = (Callback) getTargetFragment();
// Create a new instance of TimePickerDialog and return it
return new TimePickerDialog(getActivity(), this, hour, minute,
DateFormat.is24HourFormat(getActivity()));
}
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
// Do something with the time chosen by the user
timeCallback.onTimeSelected(hourOfDay + ":" + minute + ":00");
}
}
activity_main.xml
<?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">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/frameLayout"/>
</RelativeLayout>
child_fragment.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/time_edit_text"/>
</LinearLayout>
Here is the code :
AppointFragment.java
package com.example.appointapp;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.DatePicker;
import android.widget.EditText;
public class AppointFragment extends Fragment{
private static final String TAG = "AppoinFragment";
EditText chosdate, chostime;
private Appointment mappointment;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mappointment= new Appointment();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState){
View v = inflater.inflate(R.layout.fragment_appoint, parent, false);
chosdate = (EditText)v.findViewById(R.id.datea_text);
chostime = (EditText)v.findViewById(R.id.timea_text);
SetTime fromTime = new SetTime(chostime,this);
chosdate.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
DialogFragment datePickerFragment = new DatePickerFragment() {
#Override
public void onDateSet(DatePicker view, int year, int month, int day) {
Log.d(TAG, "onDateSet");
Calendar c = Calendar.getInstance();
c.set(year, month, day);
String myFormat = "dd/MM/yy";
SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.US);
chosdate.setText(sdf.format(c.getTime()));
chosdate.requestFocus();
}
};
datePickerFragment.show(getActivity().getSupportFragmentManager(), "datePicker");
}
}
});
return v;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
SetTime fromTime = new SetTime(chostime,getActivity());
}
}
SetTime.java
package com.example.appointapp;
import java.util.Calendar;
import android.app.TimePickerDialog;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.content.Context;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.widget.EditText;
import android.widget.TimePicker;
class SetTime implements OnFocusChangeListener, OnTimeSetListener {
private EditText editText;
private Calendar myCalendar;
Context ctx;
public SetTime(EditText editText, Context ctx){
this.editText = editText;
this.editText.setOnFocusChangeListener(this);
this.myCalendar = Calendar.getInstance();
}
#Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
int hour = myCalendar.get(Calendar.HOUR_OF_DAY);
int minute = myCalendar.get(Calendar.MINUTE);
new TimePickerDialog(ctx, this, hour, minute, true).show();
}
}
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
this.editText.setText( hourOfDay + ":" + minute);
}
}
SingleFragmentAcitivity.java
public abstract class SingleFragmentActivity extends FragmentActivity {
protected abstract Fragment createFragment();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fragment);
FragmentManager fm = getSupportFragmentManager();
Fragment fragment = fm.findFragmentById(R.id.fragmentContainer);
if (fragment == null) {
fragment = createFragment();
fm.beginTransaction()
.add(R.id.fragmentContainer, fragment)
.commit();
}
}
}
Appointactivity.java
package com.example.appointapp;
import android.support.v4.app.Fragment;
public class AppointActivity extends SingleFragmentActivity {
#Override
protected Fragment createFragment() {
return new AppointFragment();
}
}
Fragment_main.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="match_parent"
android:orientation="vertical" >
<Button
android:id="#+id/new_patient"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/new_patient" />
<Button
android:id="#+id/new_appoint"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/new_appoint"/>
</LinearLayout>
Fragment_appoint.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="match_parent"
android:orientation="vertical" >
<Spinner
android:id="#+id/Patients_list"
android:layout_width="117dp"
android:layout_height="wrap_content" />
<EditText
android:id="#+id/datea_text"
android:layout_width="143dp"
android:layout_height="wrap_content"
android:hint="#string/datea_text_hint" />
<EditText
android:id="#+id/timea_text"
android:layout_width="141dp"
android:layout_height="wrap_content"
android:hint="#string/timea_text_hint" />
<Button
android:id="#+id/savea_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:text="#string/savea_button" />
</LinearLayout>
Thank you for ur help
i solved the issue using the following code in my fragment:
chostime.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Calendar mcurrentTime = Calendar.getInstance();
int hour = mcurrentTime.get(Calendar.HOUR_OF_DAY);
int minute = mcurrentTime.get(Calendar.MINUTE);
TimePickerDialog mTimePicker;
mTimePicker = new TimePickerDialog(getActivity(), new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker timePicker, int selectedHour, int selectedMinute) {
chostime.setText( selectedHour + ":" + selectedMinute);
}
}, hour, minute, true);//Yes 24 hour time
mTimePicker.setTitle("Select Time");
mTimePicker.show();
}
});
Thank you

how to implement OnItemClickListener in this code?

I want to implement OnItemClickListener in this ListView ,But when i add code for this,my app will not work even there is no error. its closes automatically when I click on the Listview item. Please help me, I am a beginner in Android. I am adding my whole code here.
I am doing a bluetooth device connectivity code.
MainActivity.java
import java.util.ArrayList;
import java.util.Set;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.app.Activity;
import android.app.ProgressDialog;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
public class MainActivity extends Activity {
private TextView mStatusTv;
private Button mActivateBtn;
private Button mPairedBtn;
private Button mScanBtn;
private Button ledBtn;
private ProgressDialog mProgressDlg;
private ArrayList<BluetoothDevice> mDeviceList = new ArrayList<BluetoothDevice>();
private BluetoothAdapter mBluetoothAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mStatusTv = (TextView) findViewById(R.id.tv_status);
mActivateBtn = (Button) findViewById(R.id.btn_enable);
mPairedBtn = (Button) findViewById(R.id.btn_view_paired);
mScanBtn = (Button) findViewById(R.id.btn_scan);
ledBtn = (Button) findViewById(R.id.led);
ledBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i=new Intent(getApplicationContext(),Ledbuttons.class);
startActivity(i);
}
});
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
mProgressDlg = new ProgressDialog(this);
mProgressDlg.setMessage("Scanning...");
mProgressDlg.setCancelable(false);
mProgressDlg.setButton(DialogInterface.BUTTON_NEGATIVE, "Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
mBluetoothAdapter.cancelDiscovery();
}
});
if (mBluetoothAdapter == null) {
showUnsupported();
} else {
mPairedBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
if (pairedDevices == null || pairedDevices.size() == 0) {
showToast("No Paired Devices Found");
} else {
ArrayList<BluetoothDevice> list = new ArrayList<BluetoothDevice>();
list.addAll(pairedDevices);
Intent intent = new Intent(MainActivity.this, DeviceListActivity.class);
intent.putParcelableArrayListExtra("device.list", list);
startActivity(intent);
}
}
});
mScanBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
mBluetoothAdapter.startDiscovery();
}
});
mActivateBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mBluetoothAdapter.isEnabled()) {
mBluetoothAdapter.disable();
showDisabled();
} else {
Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(intent, 1000);
}
}
});
if (mBluetoothAdapter.isEnabled()) {
showEnabled();
} else {
showDisabled();
}
}
IntentFilter filter = new IntentFilter();
filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
filter.addAction(BluetoothDevice.ACTION_FOUND);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
registerReceiver(mReceiver, filter);
}
#Override
public void onPause() {
if (mBluetoothAdapter != null) {
if (mBluetoothAdapter.isDiscovering()) {
mBluetoothAdapter.cancelDiscovery();
}
}
super.onPause();
}
#Override
public void onDestroy() {
unregisterReceiver(mReceiver);
super.onDestroy();
}
private void showEnabled() {
mStatusTv.setText("Bluetooth is On");
mStatusTv.setTextColor(Color.BLUE);
mActivateBtn.setText("Disable");
mActivateBtn.setEnabled(true);
mPairedBtn.setEnabled(true);
mScanBtn.setEnabled(true);
ledBtn.setEnabled(true);
}
private void showDisabled() {
mStatusTv.setText("Bluetooth is Off");
mStatusTv.setTextColor(Color.RED);
mActivateBtn.setText("Enable");
mActivateBtn.setEnabled(true);
mPairedBtn.setEnabled(false);
mScanBtn.setEnabled(false);
ledBtn.setEnabled(false);
}
private void showUnsupported() {
mStatusTv.setText("Bluetooth is unsupported by this device");
mActivateBtn.setText("Enable");
mActivateBtn.setEnabled(false);
mPairedBtn.setEnabled(false);
mScanBtn.setEnabled(false);
}
private void showToast(String message) {
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
}
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)) {
final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR);
if (state == BluetoothAdapter.STATE_ON) {
showToast("Enabled");
showEnabled();
}
} else if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {
mDeviceList = new ArrayList<BluetoothDevice>();
mProgressDlg.show();
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
mProgressDlg.dismiss();
Intent newIntent = new Intent(MainActivity.this, DeviceListActivity.class);
newIntent.putParcelableArrayListExtra("device.list", mDeviceList);
startActivity(newIntent);
} else if (BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device = (BluetoothDevice) intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
mDeviceList.add(device);
showToast("Found device " + device.getName());
}
}
};
DeviceListActivity.java
import java.lang.reflect.Method;
import java.util.ArrayList;
import android.app.Activity;
import android.bluetooth.BluetoothDevice;
import android.os.Bundle;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.view.View;
import android.widget.ListView;
import android.widget.Toast;
public class DeviceListActivity extends Activity {
private ListView mListView;
private DeviceListAdapter mAdapter;
private ArrayList<BluetoothDevice> mDeviceList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDeviceList = getIntent().getExtras().getParcelableArrayList("device.list");
mListView = (ListView) findViewById(R.id.lv_paired);
mAdapter = new DeviceListAdapter(this);
mAdapter.setData(mDeviceList);
mAdapter.setListener(new DeviceListAdapter.OnPairButtonClickListener() {
#Override
public void onPairButtonClick(int position) {
BluetoothDevice device = mDeviceList.get(position);
if (device.getBondState() == BluetoothDevice.BOND_BONDED) {
unpairDevice(device);
} else {
showToast("Pairing...");
pairDevice(device);
}
}
});
mListView.setAdapter(mAdapter);
registerReceiver(mPairReceiver, new IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED));
}
#Override
public void onDestroy() {
unregisterReceiver(mPairReceiver);
super.onDestroy();
}
private void showToast(String message) {
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
}
private void pairDevice(BluetoothDevice device) {
try {
Method method = device.getClass().getMethod("createBond", (Class[]) null);
method.invoke(device, (Object[]) null);
} catch (Exception e) {
e.printStackTrace();
}
}
private void unpairDevice(BluetoothDevice device) {
try {
Method method = device.getClass().getMethod("removeBond", (Class[]) null);
method.invoke(device, (Object[]) null);
} catch (Exception e) {
e.printStackTrace();
}
}
private final BroadcastReceiver mPairReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)) {
final int state = intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE, BluetoothDevice.ERROR);
final int prevState = intent.getIntExtra(BluetoothDevice.EXTRA_PREVIOUS_BOND_STATE, BluetoothDevice.ERROR);
if (state == BluetoothDevice.BOND_BONDED && prevState == BluetoothDevice.BOND_BONDING) {
showToast("Paired");
} else if (state == BluetoothDevice.BOND_NONE && prevState == BluetoothDevice.BOND_BONDED){
showToast("Unpaired");
}
mAdapter.notifyDataSetChanged();
}
}
};
}
DeviceListAdapter.java
import java.util.List;
import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.TextView;
public class DeviceListAdapter extends BaseAdapter{
private LayoutInflater mInflater;
private List<BluetoothDevice> mData;
private OnPairButtonClickListener mListener;
public DeviceListAdapter(Context context) {
mInflater = LayoutInflater.from(context);
}
public void setData(List<BluetoothDevice> data) {
mData = data;
}
public void setListener(OnPairButtonClickListener listener) {
mListener = listener;
}
public int getCount() {
return (mData == null) ? 0 : mData.size();
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.list_item_device, null);
holder = new ViewHolder();
holder.nameTv = (TextView) convertView.findViewById(R.id.tv_name);
holder.addressTv = (TextView) convertView.findViewById(R.id.tv_address);
holder.pairBtn = (Button) convertView.findViewById(R.id.btn_pair);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
BluetoothDevice device = mData.get(position);
holder.nameTv.setText(device.getName());
holder.addressTv.setText(device.getAddress());
holder.pairBtn.setText((device.getBondState() == BluetoothDevice.BOND_BONDED) ? "Unpair" : "Pair");
holder.pairBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mListener != null) {
mListener.onPairButtonClick(position);
}
}
});
return convertView;
}
static class ViewHolder {
TextView nameTv;
TextView addressTv;
TextView pairBtn;
}
public interface OnPairButtonClickListener {
public abstract void onPairButtonClick(int position);
}
}
activity_main.xml
<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:background="#060606"
android:orientation="vertical"
android:padding="#dimen/activity_vertical_margin" >
<TextView
android:id="#+id/tv_status"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="#string/text_bluetooth_off"
android:textColor="#ff0000"
android:textSize="17sp" />
<Button
android:id="#+id/btn_enable"
android:layout_width="match_parent"
android:layout_height="33dp"
android:layout_marginTop="#dimen/activity_vertical_margin"
android:background="#585858"
android:text="#string/text_enable" />
<Button
android:id="#+id/btn_view_paired"
android:layout_width="match_parent"
android:layout_height="33dp"
android:layout_marginTop="#dimen/activity_vertical_margin"
android:background="#585858"
android:enabled="false"
android:text="#string/text_view_paired"
android:textColor="#FFFFFF" />
<Button
android:id="#+id/btn_scan"
android:layout_width="match_parent"
android:layout_height="33dp"
android:layout_marginTop="#dimen/activity_vertical_margin"
android:background="#585858"
android:enabled="false"
android:text="#string/text_scan_devices"
android:textColor="#FFFFFF" />
<Button
android:id="#+id/led"
android:layout_width="match_parent"
android:layout_height="33dp"
android:layout_marginTop="#dimen/activity_vertical_margin"
android:background="#585858"
android:enabled="false"
android:text="LEDS"
android:textColor="#FFFFFF" />
<TextView
android:id="#+id/TextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="List Of Devices"
android:textColor="#ff0000"
android:textSize="15sp" />
<ScrollView
android:id="#+id/scrollView1"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ScrollView>
<ListView
android:id="#+id/lv_paired"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
list_item_device.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"
android:paddingTop="5dp"
android:paddingBottom="5dp">
<Button
android:id="#+id/btn_pair"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:text="Pair"
android:textColor="#ff4444" />
<TextView
android:id="#+id/tv_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignTop="#+id/btn_pair"
android:layout_toLeftOf="#+id/btn_pair"
android:text="Galaxy Nexus"
android:textColor="#99cc00"
android:textSize="16sp" />
<TextView
android:id="#+id/tv_address"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/btn_pair"
android:layout_alignParentLeft="true"
android:layout_toLeftOf="#+id/btn_pair"
android:text="000000000"
android:textColor="#ffbd21" />
</RelativeLayout>
My Problems that not solved are
The app is not working when I add an onItemclicklistener to the list view.
bluetooth search result is filling with the same device name.
I cannot access the buttons after viewing pairing devices and
scanned devices(it seems like that the same layout is popping to screen).
Anyone please help me to solve these issues.
Thanks in advance.
You can just do like this -
mListView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(getApplicationContext(), " ITEM CLICKED POSITION = "+String.valueOf(position), Toast.LENGTH_SHORT).show();
}
});
You can add OnItemClickListener like this
mListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) { {
Toast.makeText(getApplicationContext(),String.valueOf(arg2), Toast.LENGTH_LONG).show();
}
});`
look at this code it contain how you set the list view listener with detect the clicked row and getting sub view in that row
ListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
View row= adapter.getView(position, view, parent);
CheckBox box=(CheckBox) row.findViewById(R.id.checkBox1);
box.performClick();
}
});
adapter is your list view adapter
hope it help

set the edittext box with the time that the TimePickerDialog set

How do I make this time picker set the edittext box with the time that the TimePickerDialog set?
package com.example.d;
import java.util.Calendar;
import android.os.Bundle;
import android.app.Activity;
import android.app.TimePickerDialog;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.view.View;
import android.widget.EditText;
public class MainActivity extends Activity {
/** Called when the activity is first created. */
int hour,min;
//static final int TIME_DIALOG_ID=0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
EditText etOne = (EditText) findViewById(R.id.editText1);
etOne.setOnClickListener(new EditText.OnClickListener() {
public void onClick(View v) {
//Do stuff here
Calendar c=Calendar.getInstance();
int hour=c.get(Calendar.HOUR);
int min=c.get(Calendar.MINUTE);
showTimeDialog(v, hour, min);
}
});
}
OnTimeSetListener timeSetListener;
public void showTimeDialog(View v, int hour, int min)
{
(new TimePickerDialog(this, timeSetListener, hour, min, true)).show();
//how do I make this time picker set the edittext box with the time that the TimePickerDialog set
}
}
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/relativeLayout1"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<EditText
android:id="#+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:width="320px">
<requestFocus />
</EditText>
</RelativeLayout>
public class MainActivity extends Activity {
int hour = -1, min = -1;
static final int TIME_DIALOG_ID = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
EditText etOne = (EditText) findViewById(R.id.editText1);
etOne.setOnClickListener(new EditText.OnClickListener() {
public void onClick(View v) {
// Do stuff here
if (hour == -1 || min == -1) {
Calendar c = Calendar.getInstance();
hour = c.get(Calendar.HOUR);
min = c.get(Calendar.MINUTE);
}
showTimeDialog(v, hour, min);
}
});
}
public void showTimeDialog(View v, int hour, int min) {
(new TimePickerDialog(MainActivity.this, timeSetListener, hour, min,
true)).show();
}
public TimePickerDialog.OnTimeSetListener timeSetListener = new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
hour = hourOfDay;
min = minute;
EditText et = (EditText) findViewById(R.id.editText1);
et.setText(hour + " : " + min);
}
};
}
You can do it in onTimeSetListener like this
private TimePickerDialog.OnTimeSetListener mTimeSetListener = new TimePickerDialog.OnTimeSetListener()
{
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute)
{
setTimeEditText.setText(hour + ":" + minute);
}
};
You have to creat an instance of OnTimeSetListener and in it's onTimeSet method you have the selected hour and minute.

Categories