How can I get the date from MaterialDatePicker? - java

My application uses MaterialDatePicker. I want to create a class that, among other data, will store the date from the MaterialDatePicker.
I have some questions:
What is the best way to save the date in the class if it is supposed to be changeable?
How to get the date from the date picker material for this?
Here's my activity where I'm using the date picker material. By clicking on the checkbox, I want to save all this information, including the date, into a class object.
Here is my code of activity with MaterialDatePicker
public class NewEvent extends AppCompatActivity {
TextInputEditText etDate, etEventId;
AutoCompleteTextView etType, etNotif;
MaterialToolbar toolbarNE;
SharedPreferences sharedPreferences;
private static final String TAG = "myLogs";
static final String newEv = "newEv";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.new_event);
final FragmentManager fragmentManager = getSupportFragmentManager();
final FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
final FirstFragment fragment1 = new FirstFragment();
etDate = findViewById(R.id.etDate);
etType = findViewById(R.id.etType);
etNotif = findViewById(R.id.etNotif);
etEventId = findViewById(R.id.etEventId);
toolbarNE = findViewById(R.id.menuNewEvent);
toolbarNE.setOnMenuItemClickListener(new MaterialToolbar.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
switch(item.getItemId())
{
case R.id.applyEvent:
/*Bundle bundle = new Bundle();
bundle.putString("name", (String) etEventId.getText().toString());
fragment1.setArguments(bundle);
fragmentTransaction.replace(R.id.q3, fragment1);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();*/
Intent intent = new Intent(NewEvent.this, FirstFragment.class);
intent.putExtra("name", (String) etEventId.getText().toString());
setResult(RESULT_OK, intent);
finish();
//Toast.makeText(getApplicationContext(), materialDatePicker.getHeaderText(), Toast.LENGTH_SHORT).show();
return true;
}
return false;
}
});
// MaterialDatePicker stuff
MaterialDatePicker.Builder builder = MaterialDatePicker.Builder.datePicker();
builder.setTitleText("Выберите дату");
final MaterialDatePicker materialDatePicker = builder.build();
etDate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
materialDatePicker.show(getSupportFragmentManager(), "DATE_PICKER");
}
});
materialDatePicker.addOnPositiveButtonClickListener(new MaterialPickerOnPositiveButtonClickListener() {
#Override
public void onPositiveButtonClick(Object selection) {
etDate.setText(materialDatePicker.getHeaderText());
}
});
// Тип события
List listEvent = new ArrayList();
Collections.addAll(listEvent, "Material", "Shit");
ArrayAdapter adapterEvent = new ArrayAdapter(this,R.layout.list_item,listEvent);
etType.setAdapter(adapterEvent);
// Тип уведомления
List listNotif = new ArrayList();
//items.add("Material");
//items.add("Shit");
Collections.addAll(listNotif, "Каждый день", "Раз в 2 дня", "Раз в 3 дня", "Раз в 5 дней", "Раз в неделю", "Не напоминать");
//String [] ITEMS = new String[] {"S1", "S2", "S3"};
//ArrayAdapter<String> ad = new ArrayAdapter<String>(this, R.layout.list_item, ITEMS);
ArrayAdapter adapterNotif = new ArrayAdapter(this,R.layout.list_item, listNotif);
etNotif.setAdapter(adapterNotif);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
}
Here is my code for the future class, but there is nothing in it yet, because I was thinking about the date.
public class Event {
public String Name;
public String Date; // I don't know what type of variable to specify here, so far I have specified a string.
public String Comment;
public String Type;
public String Notify;
Event()
{
Name = "Событие";
Date = "Date";
Comment = "Comment";
Type = "Type";
Notify = "Notify";
}
}

To get the date use:
MaterialDatePicker<Long> picker = builder.build();
picker.addOnPositiveButtonClickListener(new MaterialPickerOnPositiveButtonClickListener<Long>() {
#Override public void onPositiveButtonClick(Long selection) {
// Do something...
}
});
In this way you have the selected date as milliseconds.
If you want to format as a String you can use something like:
Calendar utc = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
utc.setTimeInMillis(selection);
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
String formatted = format.format(utc.getTime());

Related

null value on variable passed from inside a onclick response

Is there any reason why method CreatePlan won't allow me access to variable recipe_name from the onRecipeClicked function which is retrieved from the recyclerview adapter. The Log shows that the value is retrieved from the recyclerview, but I can't seem to pass it to another method.
Any help is appreciated.
Update
Also is there a way of assigning the auto incremented id created from createPlanRecipe to the id variable in createPlan?
public class CreateMealPlan extends MainActivity {
DatePicker datepicker;
Button submit;
List<com.stu54259.plan2cook.Model.Category> listRecipe = new ArrayList<>();
Cursor c;
RecyclerView recipeList;
RecipeListAdapter adapterRecipe;
String recipe_name;
EditText editPlanName;
Integer id;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.create_meal_plan);
BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.home:
Intent a = new Intent(CreateMealPlan.this,MainActivity.class);
startActivity(a);
break;
case R.id.recipes:
Intent b = new Intent(CreateMealPlan.this,RecipeSearch.class);
startActivity(b);
break;
/*case R.id.shoppingList:
Intent c = new Intent(CreateMealPlan.this, ShoppingList.class);
startActivity(c);
break;*/
case R.id.mealPlan:
Intent d = new Intent(CreateMealPlan.this, MenuPlan.class);
startActivity(d);
break;
/*case R.id.reminder:
Intent e = new Intent(CreateMealPlan.this, Reminder.class);
startActivity(e);
break*/
}
return false;
}
});
datepicker = findViewById(R.id.calendarView);
ListRecipes();
RecipeListAdapter.OnRecipeClickListener listener = new RecipeListAdapter.OnRecipeClickListener() {
public void onRecipeClicked(int position, String recipe_name) {
Log.d("Recipe selected", recipe_name);
}
};
adapterRecipe = new RecipeListAdapter(this, listRecipe, listener);
recipeList = findViewById(R.id.recipes);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(this,
LinearLayoutManager.VERTICAL, false);
recipeList.setLayoutManager(mLayoutManager);
recipeList.setItemAnimator(new DefaultItemAnimator());
recipeList.setAdapter(adapterRecipe);
submit = (Button) findViewById(R.id.create);
// perform click event on submit button
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
CreatePlan();
}
});
}
public void ListRecipes() {
listRecipe.clear();
SQLiteDatabase db = (new DatabaseManager(this).getWritableDatabase());
String selectQuery = " SELECT recipe_name, image, image2, category" + " FROM " + DatabaseManager.TABLE_RECIPE + " GROUP BY recipe_name";
c = db.rawQuery(selectQuery, null);
Log.d("Query", selectQuery);
if (c.moveToFirst()) {
do {
com.stu54259.plan2cook.Model.Category category = new com.stu54259.plan2cook.Model.Category();
category.setRecipe_name(c.getString(c.getColumnIndex("recipe_name")));
category.setImage(c.getInt(c.getColumnIndex("image")));
category.setImage2(c.getString(c.getColumnIndex("image2")));
category.setCategory_name(c.getString(c.getColumnIndex("category")));
listRecipe.add(category);
} while (c.moveToNext());
c.close();
}
}
public void CreatePlan(){
editPlanName = findViewById(R.id.editPlanName);
String plan_name = editPlanName.getText().toString();
DatabaseManager db;
int day = datepicker.getDayOfMonth();
int month = datepicker.getMonth();
int year = datepicker.getYear();
SimpleDateFormat sdf = new SimpleDateFormat("EEEE");
Integer d_name = day;
Log.d("Date", String.valueOf(d_name));
String dayOfTheWeek = sdf.format(d_name);
String date = day + "/" + month + "/" +year;
db = new DatabaseManager(getApplicationContext());
db.createPlanRecipe(d_name, dayOfTheWeek, recipe_name);
db.createPlan(plan_name, id);
}
}

Calling Class to another activity

I have a second activity that handles all the user input and another activity that handles all the data from the second activity. What I want to do is call a class "SubmitName" from the activity to the second activity so that I dont need to pass the values from second activity to the main activity anymore. Here are the codes..
MainActivity (Where the class "SubmitName" are located and values are passed.)
public class MainActivity extends AppCompatActivity {
RecyclerView recyclerView;
TextView Name;
String lastname;
String licensenumber;
String mviolation;
String maplace;
String maddress;
String phonenumber;
String officername;
String contactnumber;
String datetime;
RecyclerView.LayoutManager layoutManager;
RecyclerAdapter adapter;
ArrayList<Violator> arrayList = new ArrayList<>();
BroadcastReceiver broadcastReceiver;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button addBtn = (Button)findViewById(R.id.btnAdd);
addBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, FragActivity.class);
startActivity(intent);
}
});
recyclerView = (RecyclerView)findViewById(R.id.recyclerView);
Name = (TextView) findViewById(R.id.tvName);
Intent intent = getIntent();
String str = intent.getStringExtra("firstname");
lastname = intent.getStringExtra("lastname");
licensenumber = intent.getStringExtra("licensenumber");
mviolation = intent.getStringExtra("violation");
maplace = intent.getStringExtra("arrestplace");
maddress = intent.getStringExtra("address");
phonenumber = intent.getStringExtra("phonenumber");
contactnumber = intent.getStringExtra("contactnumber");
officername = intent.getStringExtra("officername");
datetime = intent.getStringExtra("datetime");
Name.setText(str);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(true);
adapter = new RecyclerAdapter(arrayList);
recyclerView.setAdapter(adapter);
readFromLocalStorage();
broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
readFromLocalStorage();
}
};
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.nav_bar, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.TrafficAd:
Intent i = new Intent(this, TrafficAdvisory.class);
this.startActivity(i);
break;
}
return super.onOptionsItemSelected(item);
}
public void submitName(View view)
{
String name = Name.getText().toString();
String lname = lastname;
String lnumber = licensenumber;
String violation = mviolation;
String aplace = maplace;
String address = maddress;
String pnumber = phonenumber;
String cnumber = contactnumber;
String oname = officername;
String dtime = datetime;
saveToAppServer(name,lname,lnumber,violation,aplace,address,pnumber,cnumber,oname,dtime);
Name.setText("");
}
public void readFromLocalStorage()
{
arrayList.clear();
DbHelper dbHelper = new DbHelper(this);
SQLiteDatabase database = dbHelper.getReadableDatabase();
Cursor cursor = dbHelper.readFromLocalDatabase(database);
while (cursor.moveToNext())
{
String name = cursor.getString(cursor.getColumnIndex(DBContract.NAME));
String lname = cursor.getString(cursor.getColumnIndex(DBContract.LNAME));
String lnumber = cursor.getString(cursor.getColumnIndex(DBContract.LNUMBER));
String violation = cursor.getString(cursor.getColumnIndex(DBContract.VIOLATION));
String aplace = cursor.getString(cursor.getColumnIndex(DBContract.ARRESTPLACE));
String address = cursor.getString(cursor.getColumnIndex(DBContract.ADDRESS));
String pnumber = cursor.getString(cursor.getColumnIndex(DBContract.PNUMBER));
String cnumber = cursor.getString(cursor.getColumnIndex(DBContract.CNUMBER));
String oname = cursor.getString(cursor.getColumnIndex(DBContract.ONAME));
String dtime = cursor.getString(cursor.getColumnIndex(DBContract.DTIME));
int sync_status = cursor.getInt(cursor.getColumnIndex(DBContract.SYNC_STATUS));
arrayList.add(new Violator(name,lname,lnumber,violation,aplace,address,pnumber,cnumber,oname,dtime,sync_status));
}
adapter.notifyDataSetChanged();
cursor.close();
}
public void saveToAppServer(final String name,final String lname, final String lnumber,final String violation, final String aplace,final String address, final String pnumber, final String cnumber, final String oname, final String dtime)
{
if (checkNetworkConnection())
{
StringRequest stringRequest = new StringRequest(Request.Method.POST,DBContract.SERVER_URL,
new Response.Listener<String>(){
#Override
public void onResponse(String response){
try {
JSONObject jsonObject = new JSONObject(response);
String Response = jsonObject.getString("response");
if(Response.equals("OK"))
{
saveToLocalStorage(name,lname,lnumber,violation,aplace,address,pnumber,cnumber,oname,dtime,DBContract.SYNC_STATUS_OK);
}
else
{
saveToLocalStorage(name,lname,lnumber,violation,aplace,address,pnumber,cnumber,oname,dtime,DBContract.SYNC_STATUS_FAILED);
}
} catch (JSONException e){
e.printStackTrace();
}
}
},new Response.ErrorListener(){
#Override
public void onErrorResponse(VolleyError error){
saveToLocalStorage(name,lname,lnumber,violation,aplace,address,pnumber,cnumber,oname,dtime,DBContract.SYNC_STATUS_FAILED);
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> params = new HashMap<>();
params.put("name",name);
params.put("lname",lname);
params.put("lnumber",lnumber);
params.put("violation", violation);
params.put("aplace", aplace);
params.put("address",address);
params.put("pnumber",pnumber);
params.put("cnumber",cnumber);
params.put("oname",oname);
params.put("dtime",dtime);
return params;
}
}
;
MySingleton.getInstance(MainActivity.this).addToRequestQue(stringRequest);
}
else
{
saveToLocalStorage(name,lname,lnumber,violation,aplace,address,pnumber,cnumber,oname,dtime,DBContract.SYNC_STATUS_FAILED);
}
}
SecondActivity (Where inputs are handled and data passing to the mainactivity)
public class ViolatorDetail extends AppCompatActivity implements View.OnClickListener{
EditText Name;
Button btnClose;
TextView DTime;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_violator_detail);
DTime = (TextView)findViewById(R.id.tvDTime);
final String currentDT = DateFormat.getDateTimeInstance().format(new Date());
DTime.setText(currentDT);
btnClose = (Button) findViewById(R.id.btnClose);
btnClose.setOnClickListener(this);
Button btnSubmit = (Button)findViewById(R.id.btnSubmit);
btnSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText Name = (EditText)findViewById(R.id.etfName);
EditText LName = (EditText)findViewById(R.id.etlName);
EditText LNumber = (EditText)findViewById(R.id.etlNumber);
EditText Violation = (EditText)findViewById(R.id.etViolation);
EditText Arrestplace = (EditText)findViewById(R.id.etaPlace);
EditText Address = (EditText)findViewById(R.id.etAddress);
EditText PNumber = (EditText)findViewById(R.id.etpNumber);
EditText CNumber = (EditText)findViewById(R.id.etcNumber);
EditText OName = (EditText)findViewById(R.id.etoName);
String DT = DTime.getText().toString();
Intent intent = new Intent(ViolatorDetail.this, MainActivity.class);
intent.putExtra("firstname", Name.getText().toString());
intent.putExtra("lastname", LName.getText().toString());
intent.putExtra("licensenumber", LNumber.getText().toString());
intent.putExtra("violation", Violation.getText().toString());
intent.putExtra("arrestplace", Arrestplace.getText().toString());
intent.putExtra("address", Address.getText().toString());
intent.putExtra("phonenumber", PNumber.getText().toString());
intent.putExtra("contactnumber", CNumber.getText().toString());
intent.putExtra("officername", OName.getText().toString());
intent.putExtra("datetime", DT);
startActivity(intent);
}
});
}
}
What I want to do is call the "SUBMITNAME" class to the second activity so that no data passing will be done anymore.
As other friends mentioned Intent is a correct and good way to transfer data between activities. But if you want to avoid writing so much code to transfer data I suggest to create a pure java class (or java bean) and define all needed fields in that class (note: this class should implement java.io.Serializable interface). Now you could transfer instances of this class between activities.
I don’t think there is a better way of passing data between activities than Intents.
What you probably need is encapsulation of passing of extra. You can achieve this by making a static method in the ViolatorDetail class, which accepts as arguments as values you would like to pass, and returns Intent.
public static Intent newIntent(Context packageContext, String ... args){
Intent intent = new Intent(packageContext, ViolatorDetail.this);
intent.putExtra(EXTRA_STRING_ARGS, args);
return intent;
}
Then in the caller class you make an intent by makeing a static call on that function, and pass values as arguments
Intent intent = ViolatorDetail.newIntent(getActivity(), strings)
startActivity(intent);
However, in your case, you should probably make a more sensible way of passing data than as array of strings.
If you don't want to pass data between Activities with Intent, you can do it by writing certain data in a file and when you need it just read from it... I did it like this and I'm still happy i did it that way, it's simple and relatively quick, you just have to care a little about IOExceptions.

Cant find a way to delete an item from sharedPreferences

I am trying to delete an item from taskList which is connected to sharedPreferences.
I managed to remove all items but the problem is I cant find a way to connect a counter to delete an individual item from a list that has a switch and when this switch is on true I need to remove the item from list by index number.
public class TaskAdapter extends BaseAdapter {
//transfer context
Context context;
//transfer user to use for shared preferences
String userName;
//create a list of tasks.....
List<taskItem> myTasks;
Calendar calendar = Calendar.getInstance();
PendingIntent pendingIntent;
int pos;
//constructor, for creating the adapter we need from the user context and userName
public TaskAdapter(Context context, String userName) {
this.context = context;
this.userName = userName;
//go to user shared preferences and fill the list
getData();
notifyDataSetChanged();
}
//how many item to display
#Override
public int getCount() {
//return the myTasks size....
return myTasks.size();
}
//return a specific item by index
#Override
public Object getItem(int i) {
return myTasks.get(i);
}
//return index number
#Override
public long getItemId(int i) {
return i;
}
//create our view
#Override
public View getView(final int index, final View view, ViewGroup viewGroup) {
//inflate the view inside view object -> viewInflated
final View viewInflated = LayoutInflater.from(context).inflate(R.layout.task_item, null, false);
//set our inflated view behavior
//set pointer for our inflated view
//set pointer for task name....
final TextView txtTaskName = (TextView) viewInflated.findViewById(R.id.taskName);
//set pointer for taskInfo
final TextView txtTaskInfo = (TextView) viewInflated.findViewById(R.id.taskInfo);
//set pointer for task status....
final Switch swTask = (Switch) viewInflated.findViewById(taskDone);
//set task name, by the index of my myTasks collection
txtTaskName.setText(myTasks.get(index).taskName);
//set task info, by index of myTasks collection
txtTaskInfo.setText(myTasks.get(index).taskInfo);
//set task status , switch is getting true/false
swTask.setChecked(myTasks.get(index).taskStatus);
//show date and time dialog
final ImageView dtPicker = (ImageView) viewInflated.findViewById(R.id.imgTime);
dtPicker.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final AlertDialog.Builder ad = new AlertDialog.Builder(context);
final AlertDialog aDialog = ad.create();
final LinearLayout adLayout = new LinearLayout(context);
adLayout.setOrientation(LinearLayout.VERTICAL);
TextView txtTime = new TextView(context);
txtTime.setText("Choose time");
adLayout.addView(txtTime);
final TimePicker tp = new TimePicker(context);
adLayout.addView(tp);
final DatePicker dp = new DatePicker(context);
tp.setVisibility(View.GONE);
adLayout.addView(dp);
final Button btnNext = new Button(context);
btnNext.setText("Next>");
adLayout.addView(btnNext);
btnNext.setGravity(1);
Button btnCancel = new Button(context);
btnCancel.setText("Cancel");
adLayout.addView(btnCancel);
btnCancel.setGravity(1);
btnCancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
aDialog.cancel();
}
});
btnNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final int hour = tp.getHour();
final int min = tp.getMinute();
final String myHour = String.valueOf(hour);
final String myMin = String.valueOf(min);
calendar.set(Calendar.MONTH, dp.getMonth());
calendar.set(Calendar.YEAR, dp.getYear());
calendar.set(Calendar.DAY_OF_MONTH, dp.getDayOfMonth());
dp.setVisibility(View.GONE);
tp.setVisibility(View.VISIBLE);
btnNext.setText("Finish");
btnNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
calendar.set(Calendar.HOUR_OF_DAY, tp.getHour());
calendar.set(Calendar.MINUTE, tp.getMinute());
Intent my_intent = new Intent(context, RingtonePlayingService.class);
pendingIntent = PendingIntent.getService(context, 0, my_intent, PendingIntent.FLAG_UPDATE_CURRENT);
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
if(hour > 12){
String myHour = String.valueOf(hour - 12);
}
if(min < 10)
{
String myMin = "0"+String.valueOf(min);
}
Toast.makeText(context, "Set for- "+tp.getHour()+":"+tp.getMinute() , Toast.LENGTH_LONG).show();
aDialog.cancel();
}
});
}
});
aDialog.setView(adLayout);
aDialog.show();
}
});
//create listener event, when switch is pressed
swTask.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//we using utlShared to update task status
//create instance of utlShared
utlShared myShared = new utlShared(context);
//calling method of task, and giving userName(shared preferences, taskName, taskStatus)
myShared.task(userName, txtTaskName.getText().toString(), txtTaskInfo.getText().toString(), swTask.isChecked());
//we sending a message to the user, and inform him/her about the change
Toast.makeText(context, swTask.isChecked() ? "Task done" : "Task undone", Toast.LENGTH_SHORT).show();
}
});
//return the view with the behavior.....
return viewInflated;
}
private void getData() {
//go to specific shared preferences by user name.....
SharedPreferences taskPref = context.getSharedPreferences(userName, context.MODE_PRIVATE);
//create instance of our myTasks list
myTasks = new ArrayList<>();
Map<String, ?> tasks = taskPref.getAll();
for (Map.Entry<String, ?> oneTask : tasks.entrySet()) {
//insert task to list by Key and Value, we check if value is equal to 1, becuase 1=true 0=false
for(int pos=0 ; pos<myTasks.size() ; pos++){
myTasks.get(pos);
}
String[] str = oneTask.getValue().toString().split(",");
myTasks.add(new taskItem(str[0], str[1], str[2].equals("1")));
}
}
}
And my utlShared class is
public class utlShared {
//context to use later
Context context;
//declatrtion of shared preferences object
private SharedPreferences userPref;
//declaration of shared preferences editor
private SharedPreferences.Editor editor;
public utlShared() {}
public utlShared(Context context)
{
//get context to use it
this.context=context;
//declaretion of shared preferences with file name and file mode (private,public)
userPref=context.getSharedPreferences("users",Context.MODE_PRIVATE);
//declaration of editor
editor=userPref.edit();
}
//get user and password
public void addUser(String userName, String password)
{
//stores in the phone device under data\data\package name
//put in shared preferences user name and password
editor.putString(userName,password);
//commit (save/apply) the changes.
editor.commit();
}
public boolean checkUser(String userName)
{
//get name by key->userName
String checkString = userPref.getString(userName,"na");
//print to logcat a custom message.....
Log.e("checkUser", "checkUser: "+checkString );
//check if userName equals to responded data, if it's na, we don't have the user...
return !checkString.equals("na");
}
public boolean checkUserPassword(String userName, String userPassword)
{
String checkString = userPref.getString(userName,"na");
return checkString.equals(userPassword);
}
public void task(String userName,String taskName,String taskInfo, boolean taskDone)
{
//pointer to user task shared preferences
SharedPreferences taskPref=context.getSharedPreferences(userName, Context.MODE_PRIVATE);
//create editor to change the specific shared preferences
SharedPreferences.Editor taskEditor=taskPref.edit();
//add new task -> if true write 1 else write 0
if(!taskDone){
String myData = taskName+","+taskInfo+","+(taskDone?"1":"0");
taskEditor.putString(taskName,myData);
//apply the changes
taskEditor.commit();
}
}
public void clearTasks(String userName, String taskName, String taskInfo, boolean taskDone)
{
SharedPreferences taskPref=context.getSharedPreferences(userName, Context.MODE_PRIVATE);
SharedPreferences.Editor tskEditor=taskPref.edit();
tskEditor.clear();
tskEditor.commit();
}
}
This method is called from my Welcome class which is
public class Welcome extends AppCompatActivity {
String userName;
Context context;
utlShared myUtl;
ListView taskList;
String taskName;
String taskInfo;
boolean taskDone;
AlarmManager alarmManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_welcome);
setPointer();
}
private void setPointer()
{
this.context=this;
userName=getIntent().getStringExtra("userName");
myUtl = new utlShared(context);
taskList=(ListView)findViewById(R.id.taskList);
setListData();
alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
Toast.makeText(Welcome.this, "welcome user:"+userName, Toast.LENGTH_SHORT).show();
Button btnBack = (Button)findViewById(R.id.btnBack);
FloatingActionButton btnDelete=(FloatingActionButton)findViewById(R.id.btnDelete);
btnDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
myUtl.clearTasks(userName, taskName, taskInfo, taskDone);
setListData();
}
});
btnBack.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, MainActivity.class);
startActivity(intent);
finish();
}
});
}
private void setListData() {
final TaskAdapter adapter = new TaskAdapter(context, userName);
taskList.setAdapter(adapter);
}
public void addCustomTask(View view)
{
//create builder
AlertDialog.Builder builder = new AlertDialog.Builder(context);
//set title
builder.setTitle("Add new task!");
//inflate view from layout ->custom layout,null,false as defualt values
View viewInflated= LayoutInflater.from(context).inflate(R.layout.dlg_new_task,null,false);
final EditText txtCustomLine = (EditText)viewInflated.findViewById(R.id.txtHLine);
final EditText txtCustomTask = (EditText)viewInflated.findViewById(R.id.txtTask);
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
builder.setPositiveButton("Add task", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
String myTaskCustom = txtCustomTask.getText().toString();
String myTaskLine = txtCustomLine.getText().toString();
myUtl.task(userName, myTaskCustom, myTaskLine, false);
setListData();
}
});
//display our inflated view in screen
builder.setView(viewInflated);
//show the dialog
builder.show();
}
}
Sorry for the long code but I have spent so much time on that problem and didnt find a normal way to fix it...
Thanks in advance guys, much appreciated!
taskEditor.remove('item tag');
taskEditor.commit();
Guess my question wasnt clear enough but I have found a way to do that.
if(!taskDone){
String myData = taskName+","+taskInfo+","+(taskDone?"1":"0");
taskEditor.putString(taskName,myData);
//apply the changes
taskEditor.commit();
}
else
{
taskEditor.remove(taskName);
taskEditor.commit();
adapter.notifyDataSetChanged();
}
Eventhough its not perfect because I can refresh the view after I update the Editor and only after I restart the app my last deleted tasks disappear.
Cheers and thanks a lot guys!

Want to Implements View.OnItemClickListener

i want to implements this method into my coding,but i dont know how to do it,can someone give me some suggestion on how to do it?
Below is the screenshot the coding that i want to use.
View.ONItemClickListener
this is my coding.
ViewOrder.java
public class ViewOrder extends AppCompatActivity implements ListView.OnItemClickListener {
public static final String JSON_URL = "http://dashberry.com/strack/mobile/viewOrder.php";
private ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_order);
listView = (ListView) findViewById(R.id.listView);
sendRequest();
}
private void sendRequest(){
StringRequest stringRequest = new StringRequest(JSON_URL, new Response.Listener<String>() {
public void onResponse(String response) {
showJSON(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(ViewOrder.this,error.getMessage(),Toast.LENGTH_LONG).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
private void showJSON(String json){
ParseJSON pj = new ParseJSON(json);
pj.parseJSON();
CustomList cl = new CustomList(this, ParseJSON.itemName,ParseJSON.origin,ParseJSON.destination);
listView.setAdapter(cl);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(this, ItemDetail.class);
//ParseJSON<String> map = (ParseJSON)parent.getItemAtPosition(position);
//HashMap<String,String> map = (HashMap)parent.getItemAtPosition(position);
// String empId = map.get(ParseJSON.itemName).toString();
// intent.putExtra("item_id", empId);
startActivity(intent);
}
}
ParseJSON.java
public class ParseJSON {
public static String[] itemName;
public static String[] origin;
public static String[] destination;
public static final String JSON_ARRAY = "result";
public static final String KEY_NAME = "itemName";
public static final String KEY_ORIGIN = "origin";
public static final String KEY_DESTINATION = "destination";
private JSONArray users = null;
private String json;
public ParseJSON(String json){
this.json = json;
}
protected void parseJSON(){
JSONObject jsonObject=null;
try {
jsonObject = new JSONObject(json);
users = jsonObject.getJSONArray(JSON_ARRAY);
itemName = new String[users.length()];
origin = new String[users.length()];
destination = new String[users.length()];
for(int i=0;i<users.length();i++){
JSONObject jo = users.getJSONObject(i);
itemName[i] = jo.getString(KEY_NAME);
origin[i] = jo.getString(KEY_ORIGIN);
destination[i] = jo.getString(KEY_DESTINATION);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
So basically what i want is when user click the item in the list,it will take the user to the next activity with some data(itemName).
implement onItemClick like
#Override
public void onItemClick(AdapterView<?> l, View v, int position, long id) {
//start a new Activity via Intent
Intent intent = new Intent();
intent.setClass(this, ItemDetail.class);
//you can putExtra only position or id
intent.putExtra("position", position);
intent.putExtra("id", id);
startActivity(intent);
}
You Should Create Anther Activity called ItemDetail you can get id and position by add this code in onCreate() to know which item was clicked
Intent intent = getIntent();
String position = intent.getStringExtra("position");
String id = intent.getStringExtra("id");

How to populate listview using file from internal storage?

I'm trying to make a reminder app and I used the phones internal storage to store the data being inputted. How do I read the file from the internal storage and place the strings in title in the listview of ReminderListActivity.java?
ReminderListActivity.java
public class ReminderListActivity extends ListActivity {
private static final int ACTIVITY_CREATE = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_reminder_list);
String[] items = new String[]{"Title"};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.reminder_row, R.id.text1, items);
setListAdapter(adapter);
registerForContextMenu(getListView());
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
Intent i = new Intent(this, ReminderEditActivity.class);
i.putExtra("RowId", id);
startActivity(i);
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater mi = getMenuInflater();
mi.inflate(R.menu.list_menu_item_longpress, menu);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
MenuInflater mi = getMenuInflater();
mi.inflate(R.menu.list_menu, menu);
return true;
}
#Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_insert:
createReminder();
return true;
}
return super.onMenuItemSelected(featureId, item);
}
private void createReminder() {
Intent i = new Intent(this, ReminderEditActivity.class);
startActivityForResult(i, ACTIVITY_CREATE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
}
#Override
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_delete:
return true;
}
return super.onContextItemSelected(item);
}
public void onClickSave(View view) {
Intent f = new Intent(this, ReminderEditActivity.class);
startActivity(f);
}
}
Heres the Activity I used to save the strings into the json file in the internal storage
ReminderEditActivity.java
public class ReminderEditActivity extends Activity {
private Button mDateButton;
private Button mTimeButton;
private static final int DATE_PICKER_DIALOG = 0;
private static final int TIME_PICKER_DIALOG = 1;
private Calendar mCalendar;
private static final String DATE_FORMAT = "yyyy-MM-dd";
private static final String TIME_FORMAT = "kk:m";
private static final String FILENAME = "hello.json";
private EditText TitleEditText;
private EditText BodyEditText;
private Button EditTime;
private Button EditDate;
private ArrayList<Data> data =
new ArrayList<Data>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_reminder_edit);
mCalendar = Calendar.getInstance();
mDateButton = (Button) findViewById(R.id.reminder_date);
mTimeButton = (Button) findViewById(R.id.reminder_time);
TitleEditText = (EditText) findViewById(R.id.title);
BodyEditText = (EditText) findViewById(R.id.body);
EditTime = (Button) findViewById(R.id.reminder_time);
EditDate = (Button) findViewById(R.id.reminder_date);
if (getIntent() != null) {
Bundle extras = getIntent().getExtras();
int rowId = extras != null ? extras.getInt("RowId") : -1;
registerButtonListenersAndSetDefaultText();
}
readData();
}
public void readData() {
try {
FileInputStream fis = openFileInput(FILENAME);
InputStreamReader isr = new InputStreamReader(fis, "UTF-8");
JsonReader jsonReader = new JsonReader(isr);
String title = "";
String body = "";
String time = "";
String date = "";
jsonReader.beginArray(); // [
while (jsonReader.hasNext()) {
jsonReader.beginObject(); // {
while (jsonReader.hasNext()) {
String key = jsonReader.nextName();
if (key.equals("Title")) {
title = jsonReader.nextString();
} else if (key.equals("Body")) {
body = jsonReader.nextString();
} else if (key.equals("Date")) {
date = jsonReader.nextString();
} else if (key.equals("Time")) {
time = jsonReader.nextString();
}
}
jsonReader.endObject(); // }
Data content = new Data(
title, body, date, time
);
data.add(content);
}
jsonReader.endArray();
jsonReader.close();
} catch (IOException ex) {
Toast.makeText(this, "cannot read file", Toast.LENGTH_SHORT).show();
}
}
public void addFile(View view) {
String title = TitleEditText.getText().toString();
String body = BodyEditText.getText().toString();
String time = EditTime.getText().toString();
String date = EditDate.getText().toString();
Toast.makeText(this, "File written", Toast.LENGTH_SHORT).show();
Data content = new Data(
title, body, date, time
);
data.add(content);
writeAllData();
}
public void writeAllData() {
try {
FileOutputStream fos = openFileOutput(FILENAME,
Context.MODE_PRIVATE);
OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8");
JsonWriter jsonWriter = new JsonWriter(osw);
jsonWriter.setIndent(" ");
jsonWriter.beginArray();
for (int i = 0; i < data.size(); i++) {
Data con = data.get(i);
jsonWriter.beginObject();
jsonWriter.name("Title").value(con.GetTitle());
jsonWriter.name("Body").value(con.GetBody());
jsonWriter.name("Date").value(con.GetDate());
jsonWriter.name("Time").value(con.GetTime());
jsonWriter.endObject();
}
jsonWriter.endArray();
jsonWriter.close();
} catch (IOException ex) {
Toast.makeText(this, "Cant write file", Toast.LENGTH_LONG).show();
}
}
private void registerButtonListenersAndSetDefaultText() {
mTimeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showDialog(TIME_PICKER_DIALOG);
}
});
mDateButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showDialog(DATE_PICKER_DIALOG);
}
});
updateDateButtonText();
updateTimeButtonText();
}
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DATE_PICKER_DIALOG:
return showDatePicker();
case TIME_PICKER_DIALOG:
return showTimePicker();
}
return super.onCreateDialog(id);
}
private DatePickerDialog showDatePicker() {
DatePickerDialog datePicker = new DatePickerDialog(ReminderEditActivity.this, new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
mCalendar.set(Calendar.YEAR, year);
mCalendar.set(Calendar.MONTH, monthOfYear);
mCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
updateDateButtonText();
}
}, mCalendar.get(Calendar.YEAR), mCalendar.get(Calendar.MONTH), mCalendar.get(Calendar.DAY_OF_MONTH));
return datePicker;
}
private TimePickerDialog showTimePicker() {
TimePickerDialog timePicker = new TimePickerDialog(this, new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
mCalendar.set(Calendar.HOUR_OF_DAY, hourOfDay);
mCalendar.set(Calendar.MINUTE, minute);
updateTimeButtonText();
}
}, mCalendar.get(Calendar.HOUR_OF_DAY), mCalendar.get(Calendar.MINUTE), true);
return timePicker;
}
private void updateDateButtonText() {
SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT);
String dateForButton = dateFormat.format(mCalendar.getTime());
mDateButton.setText(dateForButton);
}
private void updateTimeButtonText() {
SimpleDateFormat timeFormat = new SimpleDateFormat(TIME_FORMAT);
String timeForButton = timeFormat.format(mCalendar.getTime());
mTimeButton.setText(timeForButton);
}
}

Categories