content
stringlengths
0
3.9M
path
stringlengths
4
242
contentHash
stringlengths
1
10
package com.adempolat.composenewsapp.presentation.onboarding import androidx.annotation.DrawableRes import com.adempolat.composenewsapp.R data class Page( val title: String, val description: String, @DrawableRes val image: Int ) val pages = listOf( Page(title = "Haberler","En gnücel haberler burada", image = R.drawable.onboarding1), Page(title = "Son Dakika","bize güvenin sdsssfsf", image = R.drawable.onboarding2), Page(title = "HaLorer","En gnücdfdfdfdsfdfsdel haberler burada", image = R.drawable.onboarding3) )
Compose_NewsApp/app/src/main/java/com/adempolat/composenewsapp/presentation/onboarding/Page.kt
1408333023
package com.adempolat.composenewsapp.presentation.onboarding import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.layout.* import androidx.compose.foundation.pager.HorizontalPager import androidx.compose.foundation.pager.rememberPagerState import androidx.compose.runtime.Composable import androidx.compose.runtime.derivedStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp import com.adempolat.composenewsapp.presentation.Dimension.MediumPadding2 import com.adempolat.composenewsapp.presentation.Dimension.PageIndicatorWidth import com.adempolat.composenewsapp.presentation.common.NewsButton import com.adempolat.composenewsapp.presentation.common.NewsTextButton import com.adempolat.composenewsapp.presentation.onboarding.components.OnBoardingPage import com.adempolat.composenewsapp.presentation.onboarding.components.PageIndicator import kotlinx.coroutines.launch @OptIn(ExperimentalFoundationApi::class) @Composable fun OnBoardingScreen( onEvent: (OnBoardingEvent) -> Unit ){ Column(modifier = Modifier.fillMaxSize()) { val pagerState = rememberPagerState(initialPage = 0) { pages.size } val buttonState= remember{ derivedStateOf { when(pagerState.currentPage){ 0 -> listOf("","Next") 1 -> listOf("Back","Next") 2 -> listOf("Back","Get Started") else -> listOf("","") } } } HorizontalPager(state = pagerState) { index -> OnBoardingPage(page = pages[index]) } Spacer(modifier = Modifier.weight(1f)) Row(modifier = Modifier .fillMaxWidth() .padding(horizontal = MediumPadding2) .navigationBarsPadding(), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically) { PageIndicator(modifier= Modifier.width(PageIndicatorWidth),pageSize = pages.size, selectedPage = pagerState.currentPage) Row(verticalAlignment = Alignment.CenterVertically) { val scope = rememberCoroutineScope() if (buttonState.value[0].isNotEmpty()){ NewsTextButton(text = buttonState.value[0], onClick = { scope.launch { pagerState.animateScrollToPage(page = pagerState.currentPage - 1) } } ) } NewsButton(text = buttonState.value[1], onClick = { scope.launch { if (pagerState.currentPage == 2){ onEvent(OnBoardingEvent.SaveAppEntry) }else{ pagerState.animateScrollToPage(page = pagerState.currentPage + 1) } } }) } } Spacer(modifier = Modifier.weight(0.5f) ) } }
Compose_NewsApp/app/src/main/java/com/adempolat/composenewsapp/presentation/onboarding/OnboardingScreen.kt
2955799409
package com.giorgi.teacherdiary import androidx.test.platform.app.InstrumentationRegistry import androidx.test.ext.junit.runners.AndroidJUnit4 import org.junit.Test import org.junit.runner.RunWith import org.junit.Assert.* /** * Instrumented test, which will execute on an Android device. * * See [testing documentation](http://d.android.com/tools/testing). */ @RunWith(AndroidJUnit4::class) class ExampleInstrumentedTest { @Test fun useAppContext() { // Context of the app under test. val appContext = InstrumentationRegistry.getInstrumentation().targetContext assertEquals("com.giorgi.teacherdiary", appContext.packageName) } }
TeacherDiare/app/src/androidTest/java/com/giorgi/teacherdiary/ExampleInstrumentedTest.kt
754042397
package com.giorgi.teacherdiary import org.junit.Test import org.junit.Assert.* /** * Example local unit test, which will execute on the development machine (host). * * See [testing documentation](http://d.android.com/tools/testing). */ class ExampleUnitTest { @Test fun addition_isCorrect() { assertEquals(4, 2 + 2) } }
TeacherDiare/app/src/test/java/com/giorgi/teacherdiary/ExampleUnitTest.kt
220037475
package com.giorgi.teacherdiary import android.annotation.SuppressLint import android.content.Intent import android.os.Bundle import android.view.Menu import android.view.MenuItem import androidx.appcompat.app.AppCompatActivity import androidx.navigation.NavController import androidx.navigation.Navigation import androidx.viewpager2.widget.ViewPager2 import com.giorgi.teacherdiary.adapters.ViewpagerAdapter import com.giorgi.teacherdiary.databinding.ActivityMainBinding import com.giorgi.teacherdiary.model.StudentInfo import com.giorgi.teacherdiary.screens.addlesson.AddLessonActivity import com.giorgi.teacherdiary.screens.menu.addStudent.AddStudent import com.giorgi.teacherdiary.screens.menu.statistic.Statistic import com.giorgi.teacherdiary.screens.menu.studentList.StudentList import com.google.android.material.floatingactionbutton.FloatingActionButton import com.google.android.material.tabs.TabLayoutMediator import java.text.SimpleDateFormat import java.time.DayOfWeek import java.util.* class MainActivity : AppCompatActivity() { lateinit var binding: ActivityMainBinding lateinit var navcontroller: NavController override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) val view = binding.root setContentView(view) init() addlesson() } private fun init() { binding.viewPager.adapter = ViewpagerAdapter(this) binding.tabLayout.tabIconTint = null val calendar = Calendar.getInstance() val currentDayOfWeek = (calendar.get(Calendar.DAY_OF_WEEK) + 6) % 7 // Adjusting for your week starting from Monday TabLayoutMediator(binding.tabLayout, binding.viewPager) { tab, pos -> val dayOfWeek = (pos ) % 7 // Adjusting for your week starting from Monday val orderedDay = (dayOfWeek + 1) % 7 +1 val sdf = SimpleDateFormat("EEE", Locale.getDefault()) val dayName = sdf.format(calendar.time) when (orderedDay) { Calendar.MONDAY -> tab.text = "ორშ" Calendar.TUESDAY -> tab.text = "სამშ" Calendar.WEDNESDAY -> tab.text = "ოთხ" Calendar.THURSDAY -> tab.text = "ხუთ" Calendar.FRIDAY -> tab.text = "პარ" Calendar.SATURDAY -> tab.text = "შაბ" Calendar.SUNDAY -> tab.text = "კვი" } // Reset calendar to the current date calendar.time = Date() if (orderedDay == currentDayOfWeek) { binding.tabLayout.setScrollPosition(pos, 0f, true) } }.attach() // Set the starting position of the ViewPager to show the current day fragment val startingPosition = (currentDayOfWeek + 6) % 7 // Adjusting for your week starting from Monday binding.viewPager.setCurrentItem(startingPosition, false) binding.viewPager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() { override fun onPageSelected(position: Int) { super.onPageSelected(position) val prevPosition: Int = (calendar.get(Calendar.DAY_OF_WEEK) + 5) % 7 // Compare current position with previous position if (position > prevPosition) { val difference = position - prevPosition calendar.add(Calendar.DAY_OF_WEEK, difference) // Add one day if swiping right } else if (position < prevPosition) { val difference = prevPosition - position calendar.add(Calendar.DAY_OF_WEEK, -difference) // Subtract one day if swiping left } // Update UI val sdfCalendarDay = SimpleDateFormat("dd-MM-yyyy", Locale.getDefault()) val calendarDay = sdfCalendarDay.format(calendar.time) binding.courentTime!!.text = calendarDay } }) val currentDate = calendar.time val sdf = SimpleDateFormat("dd-MM-yyyy", Locale.getDefault()) val formattedDate = sdf.format(currentDate) binding.courentTime!!.text = formattedDate } override fun onCreateOptionsMenu(menu: Menu?): Boolean { menuInflater.inflate(com.giorgi.teacherdiary.R.menu.menu_option,menu) return super.onCreateOptionsMenu(menu) } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { com.giorgi.teacherdiary.R.id.add -> { val intent = Intent(this, AddStudent::class.java) startActivity(intent) return true } com.giorgi.teacherdiary.R.id.list_students -> { val intent = Intent(this, StudentList::class.java) startActivity(intent) return true } com.giorgi.teacherdiary.R.id.statistic -> { val intent = Intent(this, Statistic::class.java) startActivity(intent) return true } else -> return super.onOptionsItemSelected(item) } } fun addlesson(){ val floating: FloatingActionButton = binding.addLessonFloatingButton floating.setOnClickListener{ val intent = Intent(this, AddLessonActivity::class.java) startActivity(intent) } } }
TeacherDiare/app/src/main/java/com/giorgi/teacherdiary/MainActivity.kt
4048438840
package com.giorgi.teacherdiary import com.giorgi.teacherdiary.db.repository.DiaryRepository lateinit var APP: MainActivity lateinit var REPOSITORY: DiaryRepository
TeacherDiare/app/src/main/java/com/giorgi/teacherdiary/Const.kt
2004607912
package com.giorgi.teacherdiary import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import com.giorgi.teacherdiary.databinding.ActivityNestBinding class NestActivity : AppCompatActivity() { lateinit var binding: ActivityNestBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityNestBinding.inflate(layoutInflater) val view = binding.root setContentView(view) } }
TeacherDiare/app/src/main/java/com/giorgi/teacherdiary/NestActivity.kt
3777487951
package com.giorgi.teacherdiary.screens import java.util.* object CurrentData { fun getCurrentDate(): Int { val calendar = Calendar.getInstance() val year = calendar.get(Calendar.YEAR) val month = calendar.get(Calendar.MONTH) + 1 // Adding 1 because January is represented as 0 val day = calendar.get(Calendar.DAY_OF_MONTH) return day + month * 100 + year * 10000 // $day$month$year } }
TeacherDiare/app/src/main/java/com/giorgi/teacherdiary/screens/CurrentData.kt
4246514099
package com.giorgi.teacherdiary.screens.weekday.monday import android.app.Application import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.LiveData import com.giorgi.teacherdiary.REPOSITORY import com.giorgi.teacherdiary.db.repository.Database.Companion.getInstance import com.giorgi.teacherdiary.db.repository.DiaryRealisation import com.giorgi.teacherdiary.model.StudentLessons class MondayViewmodel(application: Application):AndroidViewModel(application) { val context = application fun initdatabase(){ val daoNote = getInstance(context).getStudentInfoDao() REPOSITORY = DiaryRealisation(daoNote) fun getcurrentLessons(): LiveData<List<StudentLessons>> { return REPOSITORY.lessonsForCurrentDate } } }
TeacherDiare/app/src/main/java/com/giorgi/teacherdiary/screens/weekday/monday/MondayViewmodel.kt
2097599250
package com.giorgi.teacherdiary.screens.weekday.monday import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import com.giorgi.teacherdiary.adapters.LessonsAdapter import com.giorgi.teacherdiary.databinding.FragmentMondayBinding import com.giorgi.teacherdiary.model.StudentLessons import java.text.SimpleDateFormat import java.util.* class MondayFragment : Fragment() { lateinit var binding: FragmentMondayBinding lateinit var recyclerView: RecyclerView lateinit var adapter: LessonsAdapter override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { binding = FragmentMondayBinding.inflate(layoutInflater,container,false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) recyclerView = binding.recyclerStudent val arralis = arrayListOf<StudentLessons>(StudentLessons(12, 3, "name", false, 7)) adapter = LessonsAdapter() adapter.setlist(arralis) recyclerView.adapter = adapter } }
TeacherDiare/app/src/main/java/com/giorgi/teacherdiary/screens/weekday/monday/MondayFragment.kt
3434775057
package com.giorgi.teacherdiary.screens.weekday.friday class FridayViewmodel { }
TeacherDiare/app/src/main/java/com/giorgi/teacherdiary/screens/weekday/friday/FridayViewmodel.kt
2248201240
package com.giorgi.teacherdiary.screens.weekday.friday import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.giorgi.teacherdiary.R class FridayFragment : Fragment() { override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_friday, container, false) } }
TeacherDiare/app/src/main/java/com/giorgi/teacherdiary/screens/weekday/friday/FridayFragment.kt
2774485763
package com.giorgi.teacherdiary.screens.weekday.tuesday import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.giorgi.teacherdiary.R class TuesdayFragment : Fragment() { override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_tuesday, container, false) } }
TeacherDiare/app/src/main/java/com/giorgi/teacherdiary/screens/weekday/tuesday/TuesdayFragment.kt
1235711407
package com.giorgi.teacherdiary.screens.weekday.tuesday class TuesdayViewmodel { }
TeacherDiare/app/src/main/java/com/giorgi/teacherdiary/screens/weekday/tuesday/TuesdayViewmodel.kt
2893032518
package com.giorgi.teacherdiary.screens.weekday.sunday import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.giorgi.teacherdiary.R class SundayFragment : Fragment() { override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_sunday, container, false) } }
TeacherDiare/app/src/main/java/com/giorgi/teacherdiary/screens/weekday/sunday/SundayFragment.kt
516354313
package com.giorgi.teacherdiary.screens.weekday.sunday class SundayViewmodel { }
TeacherDiare/app/src/main/java/com/giorgi/teacherdiary/screens/weekday/sunday/SundayViewmodel.kt
3466939560
package com.giorgi.teacherdiary.screens.weekday.thursday import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.giorgi.teacherdiary.R class ThursdayFragment : Fragment() { override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_thursday, container, false) } }
TeacherDiare/app/src/main/java/com/giorgi/teacherdiary/screens/weekday/thursday/ThursdayFragment.kt
2681348768
package com.giorgi.teacherdiary.screens.weekday.thursday class ThursdayViewmodel { }
TeacherDiare/app/src/main/java/com/giorgi/teacherdiary/screens/weekday/thursday/ThursdayViewmodel.kt
2394595490
package com.giorgi.teacherdiary.screens.weekday.saturday class SaturdayViewmodel { }
TeacherDiare/app/src/main/java/com/giorgi/teacherdiary/screens/weekday/saturday/SaturdayViewmodel.kt
2039133868
package com.giorgi.teacherdiary.screens.weekday.saturday import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.giorgi.teacherdiary.R class SaturdayFragment : Fragment() { override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_saturday, container, false) } }
TeacherDiare/app/src/main/java/com/giorgi/teacherdiary/screens/weekday/saturday/SaturdayFragment.kt
4089837985
package com.giorgi.teacherdiary.screens.weekday.wednesday import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.giorgi.teacherdiary.R class WednesdayFragment : Fragment() { override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_wednesday, container, false) } }
TeacherDiare/app/src/main/java/com/giorgi/teacherdiary/screens/weekday/wednesday/WednesdayFragment.kt
3937541282
package com.giorgi.teacherdiary.screens.weekday.wednesday class WednesdayViewmodel { }
TeacherDiare/app/src/main/java/com/giorgi/teacherdiary/screens/weekday/wednesday/WednesdayViewmodel.kt
361603105
package com.giorgi.teacherdiary.screens.menu.studentList import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import com.giorgi.teacherdiary.APP import com.giorgi.teacherdiary.R import com.giorgi.teacherdiary.model.StudentListModel import kotlinx.android.synthetic.main.activity_nest.* import java.io.Serializable class StudentList : AppCompatActivity(), Serializable { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_student_list) } fun init() { } companion object { fun clicknote(student: StudentListModel){ val bundle = Bundle() bundle.putSerializable("note", student) APP.navcontroller.navigate(R.id.action_mondayFragment_to_tuesdayFragment, bundle) } } }
TeacherDiare/app/src/main/java/com/giorgi/teacherdiary/screens/menu/studentList/StudentList.kt
135987606
package com.giorgi.teacherdiary.screens.menu.studentList import android.app.Application import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.LiveData import com.giorgi.teacherdiary.REPOSITORY import com.giorgi.teacherdiary.model.StudentListModel import com.giorgi.teacherdiary.model.StudentName class StudentListViewmodel(application: Application): AndroidViewModel(application) { val context = application fun getStudentList(): LiveData<List<StudentListModel>>{ return REPOSITORY.studentList } fun getStudentNames(): LiveData<List<StudentName>>{ return REPOSITORY.studentName } }
TeacherDiare/app/src/main/java/com/giorgi/teacherdiary/screens/menu/studentList/StudentListViewmodel.kt
2399158628
package com.giorgi.teacherdiary.screens.menu.statistic import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import com.giorgi.teacherdiary.R class Statistic : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_statistic) } }
TeacherDiare/app/src/main/java/com/giorgi/teacherdiary/screens/menu/statistic/Statistic.kt
1953593786
package com.giorgi.teacherdiary.screens.menu.addStudent class AddStudentViewModel { }
TeacherDiare/app/src/main/java/com/giorgi/teacherdiary/screens/menu/addStudent/AddStudentViewModel.kt
899024479
package com.giorgi.teacherdiary.screens.menu.addStudent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import com.giorgi.teacherdiary.R class AddStudent : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_add_student) } }
TeacherDiare/app/src/main/java/com/giorgi/teacherdiary/screens/menu/addStudent/AddStudent.kt
3501622983
package com.giorgi.teacherdiary.screens.addlesson import android.app.DatePickerDialog import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.text.format.DateFormat.is24HourFormat import android.widget.DatePicker import android.widget.TextView import android.widget.Toast import com.giorgi.teacherdiary.REPOSITORY import com.giorgi.teacherdiary.databinding.ActivityAddLessonBinding import com.giorgi.teacherdiary.model.StudLessonsDate import com.google.android.material.timepicker.MaterialTimePicker import com.google.android.material.timepicker.TimeFormat import kotlinx.android.synthetic.main.activity_add_lesson.view.* import java.text.SimpleDateFormat import java.util.* class AddLessonActivity : AppCompatActivity() { lateinit var binding: ActivityAddLessonBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityAddLessonBinding.inflate(layoutInflater) setContentView(binding.root) binding.timeLesson.setOnClickListener{ openTimePicker() } binding.date.setOnClickListener{ onOpenDatePickerButtonClick() } binding.saveButton.setOnClickListener{ saveLesson() } binding.backButton.setOnClickListener{ finish() } } private fun saveLesson() { val studentName = binding.studentname.text.toString() val lessonTime = binding.timeText.text.toString() val lessonDate = binding.dateText.text.toString() if (studentName.isEmpty() || lessonTime.isEmpty() || lessonDate.isEmpty() ){ Toast.makeText(this, "please full all fields", Toast.LENGTH_SHORT).show() } //val lessonData = StudLessonsDate(lessonDate, lessonTime, studentName) // REPOSITORY.addLesson(lesson) else { val lesson = StudLessonsDate(lessonDate, lessonTime, studentName) //REPOSITORY.addLesson(lesson) Toast.makeText(this, "Lesson added", Toast.LENGTH_SHORT).show() finish() } } private fun openTimePicker() { val isSystem24Hour = is24HourFormat(this) val clockFormat = if (isSystem24Hour) TimeFormat.CLOCK_24H else TimeFormat.CLOCK_12H val picker = MaterialTimePicker.Builder() .setTimeFormat(clockFormat) .setHour(12) .setMinute(0) .setTitleText("Select Appointment time") .build() val selectedTimeTextView: TextView = binding.timeText picker.addOnPositiveButtonClickListener { val selectedHour = picker.hour val selectedMinute = picker.minute // Handle the selected time as needed val selectedTime = "$selectedHour:$selectedMinute" // Update the TextView with the selected time selectedTimeTextView.text = selectedTime } picker.show(supportFragmentManager, "timePicker") } fun onOpenDatePickerButtonClick() { val calendar = Calendar.getInstance() val year = calendar.get(Calendar.YEAR) val month = calendar.get(Calendar.MONTH) val day = calendar.get(Calendar.DAY_OF_MONTH) val datePickerDialog = DatePickerDialog( this, { _: DatePicker, selectedYear: Int, selectedMonth: Int, selectedDay: Int -> val selectedDate = formatDate(selectedYear, selectedMonth, selectedDay) binding.dateText.text = selectedDate var data = selectedDate }, year, month, day ) datePickerDialog.show() } private fun formatDate(year: Int, month: Int, day: Int): String { val calendar = Calendar.getInstance() calendar.set(year, month, day) val dateFormat = SimpleDateFormat("dd/MM/yyyy", Locale.getDefault()) return dateFormat.format(calendar.time) } }
TeacherDiare/app/src/main/java/com/giorgi/teacherdiary/screens/addlesson/AddLessonActivity.kt
2501896878
package com.giorgi.teacherdiary.screens.addlesson import android.app.Application import androidx.lifecycle.AndroidViewModel import com.giorgi.teacherdiary.APP import com.giorgi.teacherdiary.REPOSITORY import com.giorgi.teacherdiary.db.dao.StudentInfoDao import com.giorgi.teacherdiary.db.repository.Database import com.giorgi.teacherdiary.db.repository.Database.Companion.getInstance import com.giorgi.teacherdiary.db.repository.DiaryRealisation import java.util.Calendar.getInstance class AddLessonViewmodel(aplication: Application) : AndroidViewModel(aplication) { }
TeacherDiare/app/src/main/java/com/giorgi/teacherdiary/screens/addlesson/AddLessonViewmodel.kt
1731767442
package com.giorgi.teacherdiary.adapters import androidx.fragment.app.Fragment import androidx.fragment.app.FragmentActivity import androidx.viewpager2.adapter.FragmentStateAdapter import com.giorgi.teacherdiary.screens.weekday.friday.FridayFragment import com.giorgi.teacherdiary.screens.weekday.monday.MondayFragment import com.giorgi.teacherdiary.screens.weekday.saturday.SaturdayFragment import com.giorgi.teacherdiary.screens.weekday.sunday.SundayFragment import com.giorgi.teacherdiary.screens.weekday.thursday.ThursdayFragment import com.giorgi.teacherdiary.screens.weekday.tuesday.TuesdayFragment import com.giorgi.teacherdiary.screens.weekday.wednesday.WednesdayFragment class ViewpagerAdapter (fragmentActivity: FragmentActivity): FragmentStateAdapter(fragmentActivity) { override fun getItemCount(): Int { return 7 } override fun createFragment(position: Int): Fragment { return when (position) { 0 -> MondayFragment() 1 -> TuesdayFragment() 2 -> ThursdayFragment() 3 -> WednesdayFragment() 4 -> FridayFragment() 5 -> SaturdayFragment() else -> return SundayFragment() } } }
TeacherDiare/app/src/main/java/com/giorgi/teacherdiary/adapters/ViewpagerAdapter.kt
583183897
package com.giorgi.teacherdiary.adapters import android.annotation.SuppressLint import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import com.giorgi.teacherdiary.R import com.giorgi.teacherdiary.model.StudentListModel import kotlinx.android.synthetic.main.item_lesson.view.name import kotlinx.android.synthetic.main.item_student_list.view.* import com.giorgi.teacherdiary.screens.menu.studentList.StudentList class ListStudentAdapter: RecyclerView.Adapter<ListStudentAdapter.ListStudentViewHolder>() { var studlist = emptyList<StudentListModel>() class ListStudentViewHolder(view: View):RecyclerView.ViewHolder(view) { } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ListStudentViewHolder { val view = LayoutInflater.from(parent.context).inflate(R.layout.item_student_list,parent,false) return ListStudentViewHolder(view) } override fun onBindViewHolder(holder: ListStudentViewHolder, position: Int) { holder.itemView.name.text = studlist[position].studentName holder.itemView.wich_class.text = studlist[position].whichClass.toString() holder.itemView.phone_number.text = studlist[position].telNumber.toString() } override fun getItemCount(): Int { return studlist.size } @SuppressLint("NotifyDataSetChanged") fun setstudlist(list : List<StudentListModel>){ studlist = list notifyDataSetChanged() } override fun onViewAttachedToWindow(holder: ListStudentViewHolder) { super.onViewAttachedToWindow(holder) holder.itemView.setOnClickListener{ StudentList.clicknote(studlist[holder.adapterPosition]) } } }
TeacherDiare/app/src/main/java/com/giorgi/teacherdiary/adapters/ListStudentAdapter.kt
2914117551
package com.giorgi.teacherdiary.adapters import android.annotation.SuppressLint import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import com.giorgi.teacherdiary.R import com.giorgi.teacherdiary.model.StudentLessons import kotlinx.android.synthetic.main.item_lesson.view.* class LessonsAdapter:RecyclerView.Adapter<LessonsAdapter.LessonsViewholder>() { var listStud = emptyList<StudentLessons>() class LessonsViewholder(view: View): RecyclerView.ViewHolder(view) { } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): LessonsViewholder { val view = LayoutInflater.from(parent.context).inflate(R.layout.item_lesson,parent,false) return LessonsViewholder(view) } override fun onBindViewHolder(holder: LessonsViewholder, position: Int) { holder.itemView.name.text = listStud[position].studentName holder.itemView.time.text = listStud[position].lessonTime.toString() holder.itemView.checkBox.isChecked = listStud[position].come holder.itemView.lessons_numb.text = listStud[position].lessonsNumber.toString() } override fun getItemCount(): Int { return listStud.size } @SuppressLint("NotifyDataSetChanged") fun setlist(list:List<StudentLessons>){ listStud = list notifyDataSetChanged() } }
TeacherDiare/app/src/main/java/com/giorgi/teacherdiary/adapters/LessonsAdapter.kt
142775799
package com.giorgi.teacherdiary.model data class StudentName ( var studentName: String, )
TeacherDiare/app/src/main/java/com/giorgi/teacherdiary/model/StudentName.kt
1747529070
package com.giorgi.teacherdiary.model import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.PrimaryKey @Entity(tableName = "student_info") data class StudentInfo( @PrimaryKey(autoGenerate = false) @ColumnInfo var studentName: String, @ColumnInfo var telNumber: Int, @ColumnInfo var subject: String, @ColumnInfo var lessonsWeek: Int, @ColumnInfo var whichClass: Int, @ColumnInfo var price: Int, @ColumnInfo var lessonsStile: Boolean = false, )
TeacherDiare/app/src/main/java/com/giorgi/teacherdiary/model/StudentInfo.kt
3687487357
package com.giorgi.teacherdiary.model import androidx.room.* //After the student arrived at the lesson @Entity(tableName = "student_lessons") data class StudentLessons( @PrimaryKey(autoGenerate = true) @ColumnInfo var lessonTime: Int, @ColumnInfo var lessonData: Int, @ColumnInfo var studentName: String, @ColumnInfo var come: Boolean = false, @ColumnInfo var lessonsNumber: Int = 1, )
TeacherDiare/app/src/main/java/com/giorgi/teacherdiary/model/StudentLessons.kt
3860129232
package com.giorgi.teacherdiary.model import androidx.room.ColumnInfo import java.io.Serializable // we must request only 3 columns in the Entity Studentinfo data class StudentListModel ( var studentName: String, var whichClass: Int, var telNumber: Int, ) : Serializable
TeacherDiare/app/src/main/java/com/giorgi/teacherdiary/model/StudentListModel.kt
878800172
package com.giorgi.teacherdiary.model import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.PrimaryKey // beafore student come to lesson @Entity(tableName = "student_lessons_date") data class StudLessonsDate( @PrimaryKey(autoGenerate = true) @ColumnInfo var lessonTimeSave: String, @ColumnInfo var lessonDataSave: String, @ColumnInfo var studentName: String, @ColumnInfo var lessonsNumber: Int = 1 )
TeacherDiare/app/src/main/java/com/giorgi/teacherdiary/model/StudLessonsDate.kt
565908756
package com.giorgi.teacherdiary.db.repository import androidx.lifecycle.LiveData import com.giorgi.teacherdiary.db.dao.StudentInfoDao import com.giorgi.teacherdiary.model.* import com.giorgi.teacherdiary.screens.CurrentData.getCurrentDate import java.util.* class DiaryRealisation(private val dao: StudentInfoDao, ): DiaryRepository { override val studentLessons: LiveData<List<StudentLessons>> get() = dao.getStudentLessons() override val studentLessonsDate: LiveData<List<StudLessonsDate>> get() = dao.getStudentLessonsDate() override val studentList: LiveData<List<StudentListModel>> get() = dao.getStudentList() override val studentName: LiveData<List<StudentName>> get() = dao.getStudentName() override val lessonsForCurrentDate: LiveData<List<StudentLessons>> get() = dao.getLessonsForCurrentDate(getCurrentDate()) override suspend fun insertStudent(studentInfo: StudentInfo, onSuccess: () -> () -> Unit) { dao.insertStudent(studentInfo) onSuccess() } override suspend fun updateStudent(studentInfo: StudentInfo, onSuccess: () -> () -> Unit) { dao.updateStudent(studentInfo) onSuccess() } override suspend fun deleteStudent(studentInfo: StudentInfo, onSuccess: () -> () -> Unit) { dao.deleteStudent(studentInfo) onSuccess() } override suspend fun insertStudentLessonsDate( studLessDate: StudLessonsDate, onSuccess: () -> () -> Unit ) { dao.insertStudentAttendLesson(studLessDate) onSuccess() } override suspend fun updateStudentLessonsDate( studLessDate: StudLessonsDate, onSuccess: () -> () -> Unit ) { dao.updateStudentAttendLesson(studLessDate) onSuccess() } override suspend fun deleteStudentLessonsDate( studLessDate: StudLessonsDate, onSuccess: () -> () -> Unit ) { dao.deleteStudentAttendLesson(studLessDate) onSuccess() } override suspend fun insertLesson( studentLessons: StudentLessons, onSuccess: () -> () -> Unit) { dao.insertLesson(studentLessons) } override suspend fun updateLesson( studentLessons: StudentLessons, onSuccess: () -> () -> Unit) { dao.updateLesson(studentLessons) } override suspend fun deleteLesson(studentLessons: StudentLessons, onSuccess: () -> () -> Unit) { dao.deleteLesson(studentLessons) onSuccess() } }
TeacherDiare/app/src/main/java/com/giorgi/teacherdiary/db/repository/DiaryRealisation.kt
714121356
package com.giorgi.teacherdiary.db.repository import androidx.lifecycle.LiveData import com.giorgi.teacherdiary.model.* interface DiaryRepository { val studentList : LiveData<List<StudentListModel>> val studentName : LiveData<List<StudentName>> val studentLessons : LiveData<List<StudentLessons>> val studentLessonsDate : LiveData<List<StudLessonsDate>> val lessonsForCurrentDate: LiveData<List<StudentLessons>> suspend fun insertStudent (studentInfo: StudentInfo, onSuccess: () -> () -> Unit) suspend fun updateStudent (studentInfo: StudentInfo, onSuccess: () -> () -> Unit) suspend fun deleteStudent (studentInfo: StudentInfo, onSuccess: () -> () -> Unit) suspend fun insertStudentLessonsDate (studLessDate:StudLessonsDate, onSuccess: () -> () -> Unit) suspend fun updateStudentLessonsDate (studLessDate:StudLessonsDate, onSuccess: () -> () -> Unit) suspend fun deleteStudentLessonsDate (studLessDate:StudLessonsDate, onSuccess: () -> () -> Unit) suspend fun insertLesson (studentLessons: StudentLessons, onSuccess: () -> () -> Unit) suspend fun updateLesson (studentLessons: StudentLessons, onSuccess: () -> () -> Unit) suspend fun deleteLesson (studentLessons: StudentLessons, onSuccess: () -> () -> Unit) }
TeacherDiare/app/src/main/java/com/giorgi/teacherdiary/db/repository/DiaryRepository.kt
16090999
package com.giorgi.teacherdiary.db.repository import androidx.room.RoomDatabase @androidx.room.Database(entities = [com.giorgi.teacherdiary.model.StudentInfo::class, com.giorgi.teacherdiary.model.StudLessonsDate::class, com.giorgi.teacherdiary.model.StudentLessons::class], version = 1) abstract class Database: RoomDatabase() { abstract fun getStudentInfoDao(): com.giorgi.teacherdiary.db.dao.StudentInfoDao companion object { @kotlin.jvm.Volatile private var database: com.giorgi.teacherdiary.db.repository.Database? = null @Synchronized fun getInstance(context: android.content.Context): com.giorgi.teacherdiary.db.repository.Database { return if (database == null) { database = androidx.room.Room.databaseBuilder(context, com.giorgi.teacherdiary.db.repository.Database::class.java, "diary").build() database as com.giorgi.teacherdiary.db.repository.Database } else { database as com.giorgi.teacherdiary.db.repository.Database } } } }
TeacherDiare/app/src/main/java/com/giorgi/teacherdiary/db/repository/Database.kt
1661048524
package com.giorgi.teacherdiary.db.dao import androidx.lifecycle.LiveData import androidx.room.* import androidx.room.Dao import com.giorgi.teacherdiary.model.* @Dao interface StudentInfoDao { @Insert(onConflict = OnConflictStrategy.IGNORE) suspend fun insertStudent(studentInfo: StudentInfo) //insert student @Update suspend fun updateStudent(studentInfo: StudentInfo) //update student @Delete suspend fun deleteStudent(studentInfo: StudentInfo) //delete student @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun insertStudentAttendLesson(studLessonsDate: StudLessonsDate) //insert lesson attend @Update suspend fun updateStudentAttendLesson(studLessonsDate: StudLessonsDate) //update lesson date @Delete suspend fun deleteStudentAttendLesson(studLessonsDate: StudLessonsDate) //delete lesson attend @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun insertLesson(studentLessons: StudentLessons) //insert student lesson @Update suspend fun updateLesson(studentLessons: StudentLessons)//update student attend lesson @Delete suspend fun deleteLesson(studentLessons: StudentLessons) //delete student lesson //StudentList where are 3 columns @Query("SELECT studentName, whichClass, telNumber FROM student_info") fun getStudentList(): LiveData<List<StudentListModel>> //StudentName list where are only one column student name @Query("SELECT studentName FROM student_info") fun getStudentName(): LiveData<List<StudentName>> //studentLessons list @Query("SELECT * FROM student_lessons") fun getStudentLessons(): LiveData<List<StudentLessons>> //studentLessonsDate list @Query("SELECT * FROM student_lessons_date") fun getStudentLessonsDate(): LiveData<List<StudLessonsDate>> @Query("SELECT * FROM student_lessons WHERE lessonData = :currentDate") fun getLessonsForCurrentDate(currentDate: Int): LiveData<List<StudentLessons>> }
TeacherDiare/app/src/main/java/com/giorgi/teacherdiary/db/dao/StudentInfoDao.kt
3776852908
package com.example.ebayhw4 import androidx.test.platform.app.InstrumentationRegistry import androidx.test.ext.junit.runners.AndroidJUnit4 import org.junit.Test import org.junit.runner.RunWith import org.junit.Assert.* /** * Instrumented test, which will execute on an Android device. * * See [testing documentation](http://d.android.com/tools/testing). */ @RunWith(AndroidJUnit4::class) class ExampleInstrumentedTest { @Test fun useAppContext() { // Context of the app under test. val appContext = InstrumentationRegistry.getInstrumentation().targetContext assertEquals("com.example.ebayhw4", appContext.packageName) } }
Ebay-Android-APP/app/src/androidTest/java/com/example/ebayhw4/ExampleInstrumentedTest.kt
2336601532
package com.example.ebayhw4 import org.junit.Test import org.junit.Assert.* /** * Example local unit test, which will execute on the development machine (host). * * See [testing documentation](http://d.android.com/tools/testing). */ class ExampleUnitTest { @Test fun addition_isCorrect() { assertEquals(4, 2 + 2) } }
Ebay-Android-APP/app/src/test/java/com/example/ebayhw4/ExampleUnitTest.kt
1764829306
package com.example.ebayhw4.ui.theme import androidx.compose.ui.graphics.Color val Purple80 = Color(0xFFD0BCFF) val PurpleGrey80 = Color(0xFFCCC2DC) val Pink80 = Color(0xFFEFB8C8) val Purple40 = Color(0xFF6650a4) val PurpleGrey40 = Color(0xFF625b71) val Pink40 = Color(0xFF7D5260)
Ebay-Android-APP/app/src/main/java/com/example/ebayhw4/ui/theme/Color.kt
1610757799
package com.example.ebayhw4.ui.theme import android.app.Activity import android.os.Build import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.material3.MaterialTheme import androidx.compose.material3.darkColorScheme import androidx.compose.material3.dynamicDarkColorScheme import androidx.compose.material3.dynamicLightColorScheme import androidx.compose.material3.lightColorScheme import androidx.compose.runtime.Composable import androidx.compose.runtime.SideEffect import androidx.compose.ui.graphics.toArgb import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalView import androidx.core.view.WindowCompat private val DarkColorScheme = darkColorScheme( primary = Purple80, secondary = PurpleGrey80, tertiary = Pink80 ) private val LightColorScheme = lightColorScheme( primary = Purple40, secondary = PurpleGrey40, tertiary = Pink40 /* Other default colors to override background = Color(0xFFFFFBFE), surface = Color(0xFFFFFBFE), onPrimary = Color.White, onSecondary = Color.White, onTertiary = Color.White, onBackground = Color(0xFF1C1B1F), onSurface = Color(0xFF1C1B1F), */ ) @Composable fun EbayHw4Theme( darkTheme: Boolean = isSystemInDarkTheme(), // Dynamic color is available on Android 12+ dynamicColor: Boolean = true, content: @Composable () -> Unit ) { val colorScheme = when { dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> { val context = LocalContext.current if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context) } darkTheme -> DarkColorScheme else -> LightColorScheme } val view = LocalView.current if (!view.isInEditMode) { SideEffect { val window = (view.context as Activity).window window.statusBarColor = colorScheme.primary.toArgb() WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = darkTheme } } MaterialTheme( colorScheme = colorScheme, typography = Typography, content = content ) }
Ebay-Android-APP/app/src/main/java/com/example/ebayhw4/ui/theme/Theme.kt
3977510927
package com.example.ebayhw4.ui.theme import androidx.compose.material3.Typography import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.sp // Set of Material typography styles to start with val Typography = Typography( bodyLarge = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 16.sp, lineHeight = 24.sp, letterSpacing = 0.5.sp ) /* Other default text styles to override titleLarge = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 22.sp, lineHeight = 28.sp, letterSpacing = 0.sp ), labelSmall = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Medium, fontSize = 11.sp, lineHeight = 16.sp, letterSpacing = 0.5.sp ) */ )
Ebay-Android-APP/app/src/main/java/com/example/ebayhw4/ui/theme/Type.kt
805710718
import android.os.Bundle import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageButton import android.widget.ImageView import android.widget.Toast import androidx.fragment.app.Fragment import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.android.volley.Request import com.android.volley.RequestQueue import com.android.volley.Response import com.android.volley.toolbox.JsonObjectRequest import com.android.volley.toolbox.Volley import com.bumptech.glide.Glide import com.example.ebayhw4.R import com.example.ebayhw4.SearchResultItem import com.example.ebayhw4.WishlistManager class PhotosFragment : Fragment() { private var title: String? = null private lateinit var requestQueue: RequestQueue private lateinit var wishlistButton: ImageButton private lateinit var product: SearchResultItem companion object { fun newInstance(title: String, product: SearchResultItem?): PhotosFragment { val fragment = PhotosFragment() val args = Bundle() args.putString("title",title) args.putParcelable("product", product) fragment.arguments = args return fragment } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) title = arguments?.getString("title") product = arguments?.getParcelable("product")!! requestQueue = Volley.newRequestQueue(requireContext()) fetchPhotos() } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { val view = inflater.inflate(R.layout.fragment_photos, container, false) wishlistButton = view.findViewById(R.id.fab) wishlistButton.setOnClickListener { toggleWishlistItem() } return view } private fun updateWishlistButtonBackground(isInWishlist: Boolean) { // Update the background of the button based on the wishlist status val drawableResource = if (isInWishlist) R.drawable.cart_remove else R.drawable.cart_plus wishlistButton.setImageResource(drawableResource) } private fun toggleWishlistItem() { val isInWishlist = WishlistManager.isItemInWishlist(product) if (isInWishlist) { WishlistManager.removeFromWishlistInApi(requireContext(), product.itemId) Toast.makeText(requireContext(), "${product.title} was removed from the wishlist",Toast.LENGTH_SHORT ).show() updateWishlistButtonBackground(WishlistManager.isItemInWishlist(product)) } else { WishlistManager.addItemToWishlist(product) Toast.makeText(requireContext(), "${product.title} was added to the wishlist",Toast.LENGTH_SHORT ).show() updateWishlistButtonBackground(WishlistManager.isItemInWishlist(product)) } updateWishlistButtonBackground(WishlistManager.isItemInWishlist(product)) } private fun fetchPhotos() { val apiUrl = "https://web-tech-hw-3.wl.r.appspot.com/photo?title=$title" Log.d("apiUrl",apiUrl) val jsonObjectRequest = JsonObjectRequest( Request.Method.GET, apiUrl, null, Response.Listener { response -> val photoList = mutableListOf<PhotoItem>() val items = response.getJSONArray("items") for (i in 0 until minOf(items.length(), 8)) { val item = items.getJSONObject(i) val imageUrl = item.getString("link") photoList.add(PhotoItem(imageUrl)) } Log.d("photoList", photoList.toString()) // Set up RecyclerView with the adapter val recyclerView = view?.findViewById<RecyclerView>(R.id.photoRecyclerView) recyclerView?.layoutManager = LinearLayoutManager(requireContext()) recyclerView?.adapter = PhotoAdapter(photoList) }, Response.ErrorListener { error -> Log.e("PhotosFragment", "Error fetching photos: ${error.message}") } ) requestQueue.add(jsonObjectRequest) } data class PhotoItem(val imageUrl: String) class PhotoAdapter(private val photoList: List<PhotosFragment.PhotoItem>) : RecyclerView.Adapter<PhotoAdapter.PhotoViewHolder>() { class PhotoViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { val imageView: ImageView = itemView.findViewById(R.id.photoImageView) } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PhotoViewHolder { val view = LayoutInflater.from(parent.context) .inflate(R.layout.item_photo, parent, false) return PhotoViewHolder(view) } override fun onBindViewHolder(holder: PhotoViewHolder, position: Int) { val photoItem = photoList[position] Glide.with(holder.itemView.context) .load(photoItem.imageUrl) .into(holder.imageView) } override fun getItemCount(): Int { return photoList.size } } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) // Find the FAB by its ID val fab = view.findViewById<ImageButton>(R.id.fab) // Set a click listener for the FAB fab.setOnClickListener { toggleWishlistItem() } } }
Ebay-Android-APP/app/src/main/java/com/example/ebayhw4/PhotosFragment.kt
3480783974
package com.example.ebayhw4 import android.content.Context import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageButton import android.widget.ImageView import android.widget.TextView import android.widget.Toast import androidx.recyclerview.widget.RecyclerView import com.squareup.picasso.Picasso class WishlistAdapter(private val wishlistItems: MutableList<WishlistItem>) : RecyclerView.Adapter<WishlistAdapter.ViewHolder>() { inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { private val itemImage: ImageView = itemView.findViewById(R.id.itemImage) private val itemTitle: TextView = itemView.findViewById(R.id.itemTitle) private val itemPrice: TextView = itemView.findViewById(R.id.price) private val zipCode: TextView = itemView.findViewById(R.id.zipCode) private val shippingInfo:TextView = itemView.findViewById(R.id.shippingCondition) private val shippingCost: TextView = itemView.findViewById(R.id.shippingCost) fun bind(item: WishlistItem) { itemTitle.text = item.title itemPrice.text = item.price Picasso.get().load(item.galleryUrl).into(itemImage) val zip = item.zipCode zipCode.text = "zip: $zip" shippingInfo.text = "Used" if(item.shippingPrice=="0.0"){ shippingCost.text = "Free" }else{ shippingCost.text = item.shippingPrice } } init { val removeButton: ImageButton = itemView.findViewById(R.id.remove_item) removeButton.setOnClickListener { val position = adapterPosition if (position != RecyclerView.NO_POSITION) { val removedItem = wishlistItems.getOrNull(position) if (removedItem != null) { removeItem(position) Toast.makeText( itemView.context, "${removedItem.title} was removed from the wishlist", Toast.LENGTH_SHORT ).show() removeItemFromWishlistApiCall(itemView.context, removedItem) } else { Log.e("WishlistAdapter", "Invalid position: $position") } } } } } fun updateItems(newItems: List<WishlistItem>) { wishlistItems.clear() wishlistItems.addAll(newItems) notifyDataSetChanged() } fun removeItemFromWishlistApiCall(context: Context, removedItem: WishlistItem) { WishlistManager.removeWishlistItem(context, removedItem) } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val view = LayoutInflater.from(parent.context).inflate(R.layout.wishlist_item, parent, false) return ViewHolder(view) } override fun onBindViewHolder(holder: ViewHolder, position: Int) { val item = wishlistItems[position] holder.bind(item) } override fun getItemCount(): Int { return wishlistItems.size } private fun removeItem(position: Int) { if (position in 0 until wishlistItems.size) { val removedItem = wishlistItems[position] wishlistItems.removeAt(position) notifyItemRemoved(position) notifyItemRangeChanged(position, wishlistItems.size) } } }
Ebay-Android-APP/app/src/main/java/com/example/ebayhw4/WishlistAdapter.kt
584328331
package com.example.ebayhw4 import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.ArrayAdapter import android.widget.Spinner import androidx.viewpager.widget.ViewPager import com.google.android.material.tabs.TabLayout class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // Find the ViewPager and TabLayout in your layout val viewPager: ViewPager = findViewById(R.id.viewPager) val tabLayout: TabLayout = findViewById(R.id.tabLayout) // Create an instance of the adapter and set it on the ViewPager val adapter = ViewPagerAdapter(supportFragmentManager) viewPager.adapter = adapter // Link the TabLayout with the ViewPager tabLayout.setupWithViewPager(viewPager) } }
Ebay-Android-APP/app/src/main/java/com/example/ebayhw4/MainActivity.kt
411945811
import android.annotation.SuppressLint import android.content.Intent import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.TextView import android.widget.Toast import androidx.appcompat.widget.AppCompatImageButton import androidx.recyclerview.widget.RecyclerView import com.example.ebayhw4.R import com.example.ebayhw4.SearchResultItem import com.example.ebayhw4.WishlistItem import com.example.ebayhw4.WishlistManager import com.example.ebayhw4.itemDetailsSplash import com.squareup.picasso.Picasso import org.json.JSONObject data class WishlistItem( val itemId: String, val title: String, val galleryUrl: String, val price: String, val shippingPrice: String, val zipCode: String, val shippingInfo: JSONObject, // Change to List or Array val returnsAccepted: Boolean ) class SearchResultsAdapter( private val productList: List<SearchResultItem>, private val searchParamsJson: String? ) : RecyclerView.Adapter<SearchResultsAdapter.ProductViewHolder>() { private var latestClickedPosition: Int = RecyclerView.NO_POSITION override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ProductViewHolder { val view = LayoutInflater.from(parent.context).inflate(R.layout.item_search_result, parent, false) return ProductViewHolder(view) } override fun onBindViewHolder(holder: ProductViewHolder, @SuppressLint("RecyclerView") position: Int) { val product = productList[position] holder.titleTextView.text = product.title holder.zipCodeTextView.text ="Zip: ${product.zipCode}" holder.shippingCostTextView.text = product.shippingPrice holder.conditon.text = product.shippingCondition holder.price.text = product.price var itemId:Any = product.itemId val wishlistItem = WishlistItem( itemId = product.itemId, title = product.title, galleryUrl = product.galleryUrl, price = product.price, shippingPrice = product.shippingPrice, zipCode = product.zipCode, shippingInfo = JSONObject(), returnsAccepted = true ) Picasso.get().load(product.galleryUrl).into(holder.imageView) val isItemInWishlist = WishlistManager.isItemInWishlist(product) updateWishlistButtonBackground(holder.imageButton, isItemInWishlist ) holder.imageButton.setOnClickListener { if (isItemInWishlist) { WishlistManager.removeItemFromWishlist(wishlistItem) Toast.makeText( holder.itemView.context, "${product.title} was removed from the wishlist", Toast.LENGTH_SHORT ).show() } else { WishlistManager.addItemToWishlist(product) Toast.makeText( holder.itemView.context, "${product.title} was added to the wishlist", Toast.LENGTH_SHORT ).show() } // Update the background of the button after toggling updateWishlistButtonBackground(holder.imageButton, !isItemInWishlist) } holder.itemView.setOnClickListener{ val intent = Intent(holder.itemView.context, itemDetailsSplash::class.java) latestClickedPosition = position intent.putExtra("productId",product.itemId) intent.putExtra("title",product.title) intent.putExtra("searchParams",searchParamsJson) intent.putExtra("shippingCost",product.shippingPrice) intent.putExtra("product", product) intent.putExtra("position", latestClickedPosition) holder.itemView.context.startActivity(intent) } } private fun updateWishlistButtonBackground(button: AppCompatImageButton, isInWishlist: Boolean) { // Update the background of the button based on the wishlist status val drawableResource = if (isInWishlist) R.drawable.wishlist_remove else R.drawable.ic_launcher_wishlist_round button.setBackgroundResource(drawableResource) } override fun getItemCount(): Int { return productList.size } class ProductViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { val imageView: ImageView = itemView.findViewById(R.id.imageView) val titleTextView: TextView = itemView.findViewById(R.id.titleTextView) val zipCodeTextView: TextView = itemView.findViewById(R.id.zipCodeTextView) val shippingCostTextView: TextView = itemView.findViewById(R.id.shippingCostTextView) val imageButton = itemView.findViewById<AppCompatImageButton>(R.id.addToWishlistButton) val conditon: TextView = itemView.findViewById(R.id.conditionTextView) val price:TextView = itemView.findViewById(R.id.productCostTextView) } }
Ebay-Android-APP/app/src/main/java/com/example/ebayhw4/SearchResultsAdapter.kt
812455840
package com.example.ebayhw4 import android.os.Bundle import android.view.View import android.widget.LinearLayout import android.widget.TextView import androidx.fragment.app.Fragment import androidx.lifecycle.Observer import androidx.recyclerview.widget.GridLayoutManager import androidx.recyclerview.widget.RecyclerView class WishListFragment : Fragment(R.layout.fragment_wishlist) { private lateinit var wishlistRecyclerView: RecyclerView private lateinit var noItemsTextView: TextView private lateinit var wishlistCardView: androidx.cardview.widget.CardView private lateinit var wishlistAdapter: WishlistAdapter private lateinit var itemCountTextView: TextView private lateinit var totalTextView: TextView private lateinit var linearLayout2: LinearLayout override fun onResume() { super.onResume() // Fetch the latest wishlist items when the fragment is resumed WishlistManager.getAllWishlistItemsFromApi() } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) WishlistManager.init(requireContext()) wishlistRecyclerView = view.findViewById(R.id.wishlistRecyclerView) noItemsTextView = view.findViewById(R.id.noItemsTextView) wishlistCardView = view.findViewById(R.id.wishlistCardView) itemCountTextView = view.findViewById(R.id.itemCount) totalTextView = view.findViewById(R.id.total) linearLayout2 = view.findViewById(R.id.linearLayout2) // Observe changes in wishlistLiveData WishlistManager.wishlistLiveData.observe(viewLifecycleOwner, Observer { wishlistItems -> updateUI(wishlistItems) }) val layoutManager = GridLayoutManager(context, 2) wishlistRecyclerView.layoutManager = layoutManager // Initialize the wishlistAdapter only once wishlistAdapter = WishlistAdapter(ArrayList(WishlistManager.getWishlist())) // Convert to mutable list wishlistRecyclerView.adapter = wishlistAdapter WishlistManager.getAllWishlistItemsFromApi() } private fun updateUI(wishlistItems: List<WishlistItem>?) { if (wishlistItems?.size!! > 0) { linearLayout2.visibility = View.GONE wishlistCardView.visibility = View.GONE noItemsTextView.visibility = View.GONE totalTextView.visibility = View.VISIBLE itemCountTextView.visibility = View.VISIBLE wishlistAdapter.updateItems(wishlistItems) // Add this line val totalCount = wishlistItems.size val totalPrice = calculateTotalPrice(wishlistItems) itemCountTextView.text = "WishList Total($totalCount items)" totalTextView.text = "$$totalPrice" } else { linearLayout2.visibility = View.VISIBLE wishlistCardView.visibility = View.VISIBLE noItemsTextView.visibility = View.VISIBLE totalTextView.visibility = View.GONE itemCountTextView.visibility = View.GONE } } private fun calculateTotalPrice(wishlistItems: List<WishlistItem>): Double { var total = 0.0 for (item in wishlistItems) { total += item.price.toDouble() } return total } }
Ebay-Android-APP/app/src/main/java/com/example/ebayhw4/WishListFragment.kt
686503463
package com.example.ebayhw4 import androidx.fragment.app.Fragment import androidx.fragment.app.FragmentManager import androidx.fragment.app.FragmentPagerAdapter class ViewPagerAdapter(fm: FragmentManager) : FragmentPagerAdapter(fm) { override fun getItem(position: Int): Fragment { return when (position) { 0 -> SearchFragment() 1 -> WishListFragment() else -> throw IllegalArgumentException("Invalid position: $position") } } override fun getCount(): Int { return 2 // Number of tabs } override fun getPageTitle(position: Int): CharSequence? { // Set tab titles (if needed) return when (position) { 0 -> "Search" 1 -> "WishList" else -> null } } }
Ebay-Android-APP/app/src/main/java/com/example/ebayhw4/ViewPagerAdapter.kt
1793551703
package com.example.ebayhw4 import android.annotation.SuppressLint import android.content.Intent import android.os.Bundle import android.os.Handler import android.view.MenuItem import android.widget.ProgressBar import android.widget.TextView import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.widget.Toolbar class LoadScreen : AppCompatActivity() { private lateinit var progressBar: ProgressBar private lateinit var titleTextView: TextView @SuppressLint("MissingInflatedId") override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_load_screen) val toolbar: Toolbar = findViewById(R.id.toolbar) setSupportActionBar(toolbar) supportActionBar?.setDisplayHomeAsUpEnabled(true) val searchParamsJson = intent.getStringExtra("Search_PARAMS") // scheduleSplashScreen(searchParamsJson) progressBar = findViewById(R.id.progressBar) titleTextView = findViewById(R.id.textView4) // Set the initial title titleTextView.text = "Searching Products ..." // Start the splash screen timer scheduleSplashScreen(searchParamsJson) } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { android.R.id.home -> { // navigateUpToMain() navigateUpToSearchResults() return true } } return super.onOptionsItemSelected(item) } private fun navigateUpToSearchResults() { // Create an Intent to navigate up to the SearchResults activity val searchResultsIntent = Intent(this, MainActivity::class.java) // Add any extras you need to pass to the SearchResults activity // searchResultsIntent.putExtra("Search_PARAMS", searchParamsJson) // Navigate up to the SearchResults activity startActivity(searchResultsIntent) // Finish the current activity (itemDetailsSplash) finish() } private fun scheduleSplashScreen(searchParamsJson: String?) { val splashScreenDuration = getSplashScreenDuration() Handler().postDelayed( { // After the splash screen duration, start the SearchResults activity startSearchResultsActivity(searchParamsJson) finish() }, splashScreenDuration ) } private fun startSearchResultsActivity(searchParamsJson: String?) { // Create an Intent to start the SearchResults activity val searchResultsIntent = Intent(this, SearchResults::class.java) // Put the search parameters as extras to the intent searchResultsIntent.putExtra("Search_PARAMS", searchParamsJson) // Start the SearchResults activity startActivity(searchResultsIntent) } private fun getSplashScreenDuration() = 2000L }
Ebay-Android-APP/app/src/main/java/com/example/ebayhw4/LoadScreen.kt
1193475334
package com.example.ebayhw4 import android.content.Intent import android.net.Uri import android.os.Bundle import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.AdapterView import android.widget.ArrayAdapter import android.widget.ImageButton import android.widget.ImageView import android.widget.LinearLayout import android.widget.Spinner import android.widget.TextView import android.widget.Toast import androidx.cardview.widget.CardView import androidx.fragment.app.Fragment import com.android.volley.Request import com.android.volley.RequestQueue import com.android.volley.toolbox.JsonArrayRequest import com.android.volley.toolbox.Volley import com.bumptech.glide.Glide data class SimilarProduct( val imageURL: String, val title: String, val shippingCost: String, var timeLeft: String, val buyItNowPrice: String, val viewItemURL: String ) class SimilarFragment : Fragment() { private var itemId: String? = null private lateinit var view: View private var noresult: TextView? = null private var similarSortSpinner: Spinner? = null private lateinit var requestQueue: RequestQueue private var similarProductList: MutableList<SimilarProduct> = mutableListOf() val sortItems = arrayOf("Default", "Name", "Price", "Days") private val orderItems = arrayOf("Ascending", "Descending") private var currentSortItemPosition: Int = 0 private var currentOrderItemPosition: Int = 0 private var masterProductList: MutableList<SimilarProduct> = mutableListOf() private var displayProductList: MutableList<SimilarProduct> = mutableListOf() private lateinit var wishlistButton: ImageButton private lateinit var product: SearchResultItem companion object { fun newInstance(itemId: String, product: SearchResultItem?): SimilarFragment { val fragment = SimilarFragment() val args = Bundle() args.putString("itemId", itemId) args.putParcelable("product", product) fragment.arguments = args return fragment } } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { itemId = arguments?.getString("itemId") view = inflater.inflate(R.layout.fragment_similar, container, false) noresult = view?.findViewById(R.id.no_result) // Use safe call product = arguments?.getParcelable("product")!! requestQueue = Volley.newRequestQueue(requireContext()) wishlistButton = view.findViewById(R.id.fab) wishlistButton.setOnClickListener { toggleWishlistItem() } return view } private fun updateWishlistButtonBackground(isInWishlist: Boolean) { // Update the background of the button based on the wishlist status val drawableResource = if (isInWishlist) R.drawable.cart_remove else R.drawable.cart_plus wishlistButton.setImageResource(drawableResource) } private fun toggleWishlistItem() { val isInWishlist = WishlistManager.isItemInWishlist(product) if (isInWishlist) { WishlistManager.removeFromWishlistInApi(requireContext(), product.itemId) Toast.makeText(requireContext(), "${product.title} was removed from the wishlist", Toast.LENGTH_SHORT ).show() } else { WishlistManager.addItemToWishlist(product) Toast.makeText(requireContext(), "${product.title} was added to the wishlist", Toast.LENGTH_SHORT ).show() } updateWishlistButtonBackground(WishlistManager.isItemInWishlist(product)) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) noresult?.visibility = View.INVISIBLE val similarItemSpinner: Spinner = view.findViewById(R.id.similar_content) similarSortSpinner = view.findViewById(R.id.similar_sort) val productImageView = view.findViewById<ImageView>(R.id.product_images) val sortAdapter = ArrayAdapter( requireContext(), android.R.layout.simple_spinner_dropdown_item, sortItems ) sortAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item) similarItemSpinner?.adapter = sortAdapter val orderAdapter = ArrayAdapter( requireContext(), android.R.layout.simple_spinner_dropdown_item, orderItems ) orderAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item) similarSortSpinner?.adapter = orderAdapter makeApiCall() // Replace "imageUrlFromApi" with the actual URL from your JSON response val imageUrlFromApi = "https://www.google.com/url?sa=i&url=https%3A%2F%2Fwww.salveinternational.org%2Fcould-you-become-an-ebay-seller-for-s-a-l-v-e%2F&psig=AOvVaw08fxaoViMNBZiKEhfgc8vz&ust=1701636387651000&source=images&cd=vfe&ved=0CBEQjRxqFwoTCJDm1NXP8YIDFQAAAAAdAAAAABAI" super.onViewCreated(view, savedInstanceState) // Load the image using Glide if (productImageView != null) { Glide.with(this) .load(imageUrlFromApi) .placeholder(R.drawable.wishlist) .error(R.drawable.wishlist) .into(productImageView) } else { Log.e("Glide", "productImageView is null") } similarItemSpinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener { override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) { // Check if "Default" is selected if (sortItems[position] == "Default" || sortItems[position]!="Price") { similarSortSpinner?.isEnabled = false } else { similarSortSpinner?.isEnabled = true sortAndDisplayData( sortItems[position], orderItems[similarSortSpinner?.selectedItemPosition ?: 0] ) } currentSortItemPosition = position // Enable similarSortSpinner when an option other than "Default" is selected similarSortSpinner?.isEnabled = sortItems[position] != "Default" } override fun onNothingSelected(parent: AdapterView<*>?) { // Do nothing here } } setSimilarSortSpinnerListener(view) } private fun sortAndDisplayData(sortField: String, sortOrder: String) { // Update the displayProductList based on the selected sort criteria and order displayProductList = when (sortField) { "Name" -> { if (sortOrder == "Ascending") masterProductList.sortedBy { it.title } else masterProductList.sortedByDescending { it.title } } "Price" -> { if (sortOrder == "Ascending") masterProductList.sortedBy { it.buyItNowPrice.toDoubleOrNull() ?: 0.0 } else masterProductList.sortedByDescending { it.buyItNowPrice.toDoubleOrNull() ?: 0.0 } } "Days" -> { masterProductList.sortedByDescending { if(sortOrder=="Ascending") it.timeLeft.toIntOrNull() ?: Int.MAX_VALUE else -it.timeLeft.toIntOrNull()!! ?: Int.MAX_VALUE } } else -> masterProductList // Default or unknown sort field, maintain the original order }.toMutableList() Log.d("masterProduct",displayProductList.toString()) // Update the order position currentOrderItemPosition = if (sortOrder == "Descending") 1 else 0 // Log the sorted list for debugging // Update the UI with the sorted data updateProductList(view, displayProductList) } private fun updateProductList(view: View, sortedList: List<SimilarProduct>) { val productContainer = view.findViewById<LinearLayout>(R.id.card) val inflater = LayoutInflater.from(requireContext()) productContainer?.removeAllViews() for (product in sortedList) { // Inflate the layout for each item val productItemView = inflater.inflate(R.layout.product_layout_item, productContainer, false) val productImageView = productItemView.findViewById<ImageView>(R.id.product_images) val productTitleTextView = productItemView.findViewById<TextView>(R.id.product_title) val shippingInfoTextView = productItemView.findViewById<TextView>(R.id.shipping_info) val productPriceTextView = productItemView.findViewById<TextView>(R.id.product_price) val productDateTextView: TextView = productItemView.findViewById<TextView>(R.id.days_left) // Load the image using Glide if (!product.imageURL.isNullOrEmpty()) { Glide.with(this) .load(product.imageURL) .placeholder(R.drawable.wishlist) .error(R.drawable.wishlist) .into(productImageView) } else { productImageView.setImageResource(R.drawable.wishlist) } // Set text for other TextViews productTitleTextView.text = product.title shippingInfoTextView.text = product.shippingCost productPriceTextView.text = product.buyItNowPrice if(product.timeLeft.isNullOrBlank() or product.timeLeft.isNullOrEmpty()){ productDateTextView.text = "0 Days Left" } productDateTextView.text = "${product.timeLeft} Days Left" productContainer?.addView(productItemView) } } private fun setSimilarSortSpinnerListener(view: View) { similarSortSpinner?.onItemSelectedListener = object : AdapterView.OnItemSelectedListener { override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) { // Ensure that similarItemSpinner is not null before accessing its selected item position val selectedItemPosition = similarSortSpinner?.selectedItemPosition ?: 0 val sortField = sortItems[selectedItemPosition] val sortOrder = orderItems[position] if (sortField != "Default") { similarSortSpinner?.isEnabled = true // If any other option is selected, update the display based on the selected sort criteria and order sortAndDisplayData(sortField, sortOrder) }else{ similarSortSpinner?.isEnabled = false sortAndDisplayData(sortItems[currentSortItemPosition], orderItems[currentOrderItemPosition]) } } override fun onNothingSelected(parent: AdapterView<*>?) { // Do nothing here } } } private fun makeApiCall() { val url = "https://web-tech-hw-3.wl.r.appspot.com/similar-products/$itemId" val jsonProductObjectRequest = JsonArrayRequest( Request.Method.GET, url, null, { response -> try { masterProductList.clear() displayProductList.clear() val rootView = view.findViewById<LinearLayout>(R.id.product_list_container) val inflater = LayoutInflater.from(requireContext()) for (i in 0 until response.length()) { val item = response.getJSONObject(i) val imageURL = item.optString("imageURL", "") val title = item.optString("title", "N/A") val viewItemURL = item.optString("viewItemURL", "https://www.ebay.com/") val shippingCost = item.getJSONObject("shippingCost").optString("__value__", "N/A") var timeLeft = item.optString("timeLeft", "3") var Pattern = Regex("""P(\d+)D""") val Result = Pattern.find(timeLeft) val extracted = Result?.groups?.get(1)?.value timeLeft = extracted var timeLeftInt = timeLeft.toIntOrNull() if (timeLeftInt == null) { // If parsing fails, try to extract a numeric value using a regex pattern val numberPattern = Regex("""(\d+)""") val matchResult = numberPattern.find(timeLeft) timeLeftInt = matchResult?.groups?.get(1)?.value?.toIntOrNull() } if (timeLeftInt == null) { timeLeftInt = Int.MAX_VALUE } var buyItNowPrice = item.getJSONObject("buyItNowPrice").optString("__value__", "N/A") // Create a SimilarProduct object and add it to the list val similarProduct = SimilarProduct(imageURL, title, shippingCost, timeLeft.toString(), buyItNowPrice, viewItemURL) masterProductList.add(similarProduct) // Inflate the layout for each item val productItemView = inflater.inflate(R.layout.product_layout_item, rootView, false) // Find views in the inflated layout val productImageView = productItemView.findViewById<ImageView>(R.id.product_images) val productTitleTextView = productItemView.findViewById<TextView>(R.id.product_title) val shippingInfoTextView = productItemView.findViewById<TextView>(R.id.shipping_info) val productPriceTextView = productItemView.findViewById<TextView>(R.id.product_price) val dateTextView: TextView = productItemView.findViewById<TextView>(R.id.days_left) // Load the image using Glide if (!imageURL.isNullOrEmpty()) { Glide.with(this) .load(imageURL) .placeholder(R.drawable.wishlist) .error(R.drawable.wishlist) .into(productImageView) } else { // Handle the case where imageURL is null or empty // For example, you might want to set a default image productImageView.setImageResource(R.drawable.wishlist) } // Set text for other TextViews productTitleTextView.text = title shippingInfoTextView.text = "$shippingCost" productPriceTextView.text = "$buyItNowPrice" val numberPattern = Regex("""P(\d+)D""") val matchResult = numberPattern.find(timeLeft) val extractedNumber = matchResult?.groups?.get(1)?.value // Inflate the layout for each item if(extractedNumber==null){ dateTextView.text = "1 Days Left" }else{ dateTextView.text = "$extractedNumber Days Left" } // Set the click listener for the CardView val cardView: CardView = productItemView.findViewById(R.id.product_card) cardView.setOnClickListener { // Open the website using an Intent val intent = Intent(Intent.ACTION_VIEW, Uri.parse(viewItemURL)) startActivity(intent) } // Add the inflated layout to the main container rootView.addView(productItemView) } Log.d("master",masterProductList.toString()) // Now that the UI is updated, set the item selected listener for similarSortSpinner setSimilarSortSpinnerListener(view) } catch (e: Exception) { e.printStackTrace() } }, { error -> // Handle errors here Log.e("responseSimilar", "Error: ${error.message}") } ) requestQueue.add(jsonProductObjectRequest) } }
Ebay-Android-APP/app/src/main/java/com/example/ebayhw4/SimilarFragment.kt
1829720451
package com.example.ebayhw4 import android.content.Intent import android.graphics.Color import android.net.Uri import android.os.Bundle import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageButton import android.widget.ImageView import android.widget.TextView import android.widget.Toast import androidx.core.content.ContextCompat import androidx.fragment.app.Fragment import com.android.volley.Request import com.android.volley.RequestQueue import com.android.volley.Response import com.android.volley.toolbox.JsonObjectRequest import com.android.volley.toolbox.Volley import org.json.JSONObject import kotlin.properties.Delegates class ShippingFragment : Fragment() { private var itemId: String? = null private var searchParamsJson:String? = null private var shippingCost:String? = null private lateinit var requestQueue: RequestQueue private lateinit var wishlistButton: ImageButton private lateinit var product: SearchResultItem private var location by Delegates.notNull<Int>() companion object { private const val ARG_ItemId = "itemId" private const val ARG_SEARCH_PARAMS = "searchParamsJson" private const val ARG_Shipping = "shippingCost" fun newInstance( itemId: String, searchParams: String, shippingCost: String, product: SearchResultItem?, location: Int ): ShippingFragment { val fragment = ShippingFragment() val args = Bundle() args.putString(ARG_ItemId,itemId) args.putString(ARG_SEARCH_PARAMS,searchParams) args.putString(ARG_Shipping,shippingCost) args.putParcelable("product", product) args.putInt("location",location) fragment.arguments = args return fragment } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) itemId = arguments?.getString("itemId") searchParamsJson = arguments?.getString("searchParamsJson") shippingCost = arguments?.getString("shippingCost") product = arguments?.getParcelable("product")!! location = arguments?.getInt("location")!! requestQueue = Volley.newRequestQueue(requireContext()) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) // Access the ImageView and apply color filter val truckDeliveryImageView = view.findViewById<ImageView>(R.id.imageView2) truckDeliveryImageView?.setColorFilter(resources.getColor(android.R.color.black), android.graphics.PorterDuff.Mode.SRC_IN) // Now you can proceed with other operations fetchShippingDetails() fetchProductDetails() } private fun fetchProductDetails() { val productUrl = "https://web-tech-hw-3.wl.r.appspot.com/search-results?searchParams=$searchParamsJson" val jsonProductObjectRequest = JsonObjectRequest( Request.Method.GET, productUrl, null, { response -> try { val jsonResponse = JSONObject(response.toString()) val searchResults = jsonResponse.getJSONArray("searchResult") Log.d("SearchResults",searchResults.toString()) var storeName = "" var storeURL = "" val item = searchResults.getJSONObject(0).getJSONArray("item").getJSONObject(location) Log.d("item",item.toString()) val storeInfoArray = item.optJSONArray("storeInfo") if (storeInfoArray != null && storeInfoArray.length() > 0) { storeName = storeInfoArray.getJSONObject(0).optJSONArray("storeName")?.optString(0, "") ?: "" storeURL = storeInfoArray.getJSONObject(0).optJSONArray("storeURL")?.optString(0, "") ?: "" } else { storeName = "USAEasySales" storeURL = "http://stores.ebay.com/USAEasySales" } val firstItem = item val name = view?.findViewById<TextView>(R.id.storeUrl) name?.text = storeName name?.setOnClickListener{ val intent = Intent(Intent.ACTION_VIEW, Uri.parse(storeURL)) startActivity(intent) } Log.d("storeName",storeName) Log.d("StoreUrl",storeURL) Log.d("firstItem",firstItem.toString()) val returnsAcceptedArray = firstItem.getJSONArray("returnsAccepted") Log.d("returnsAcceptedArray",returnsAcceptedArray.toString()) val returnsAccepted = returnsAcceptedArray.getString(0) // Extracting shippingInfo val shippingInfoArray = firstItem.getJSONArray("shippingInfo") val shippingInfo = shippingInfoArray.getJSONObject(0) val sellerInfoArray = firstItem.getJSONArray("sellerInfo") val sellerInfo = sellerInfoArray.getJSONObject(0) // Extracting specific seller details val sellerUserName = sellerInfo.getJSONArray("sellerUserName").getString(0) val feedbackScore = sellerInfo.getJSONArray("feedbackScore").getString(0) Log.d("feedbackScore",feedbackScore) var score = view?.findViewById<TextView>(R.id.score) if(feedbackScore.isNotEmpty()){ score?.text = feedbackScore.toString() }else{ score?.visibility = View.GONE } val positiveFeedbackPercent = sellerInfo.getJSONArray("positiveFeedbackPercent").getString(0) val positivePercent = view?.findViewById<TextView>(R.id.popularityscore) positivePercent?.text = positiveFeedbackPercent.toString() val feedbackRatingStar = sellerInfo.getJSONArray("feedbackRatingStar").getString(0) Log.d("feedbackRatingStart",feedbackRatingStar) val topRatedSeller = sellerInfo.getJSONArray("topRatedSeller").getString(0) val feedbackScoreText = view?.findViewById<TextView>(R.id.score) feedbackScoreText?.text = feedbackScore val positiveScore = view?.findViewById<TextView>(R.id.popularityscore) positiveScore?.text = "$positiveFeedbackPercent %" Log.d("positiveFeedback",positiveFeedbackPercent) // Assuming feedbackScore is an integer val feedbackStarImageView = view?.findViewById<ImageView>(R.id.star) val feedbackRatingStarColor = Color.parseColor(feedbackRatingStar) val starDrawable = ContextCompat.getDrawable(requireContext(),R.drawable.star_circle) if(feedbackScore.toInt()>10000){ feedbackStarImageView?.setImageResource(R.drawable.star_circle_outline) } starDrawable?.setTint(feedbackRatingStarColor) feedbackStarImageView?.setImageDrawable(starDrawable) val shippingType = shippingInfo.getJSONArray("shippingType").getString(0) val shipToLocations = shippingInfo.getJSONArray("shipToLocations").getString(0) var shipping = view?.findViewById<TextView>(R.id.shippingCostTextView) Log.d("shippingCost",shippingCost.toString()) if (shippingCost != null && shippingCost.toString().isNotEmpty() && shippingCost != "Free") { shipping?.text = "$ $shippingCost" } else { shipping?.text = "Free" } val oneDayShippingAvailable = shippingInfo.getJSONArray("oneDayShippingAvailable").getString(0) val handlingTime = shippingInfo.getJSONArray("handlingTime").getString(0) var handlingText = view?.findViewById<TextView>(R.id.handlingTimeInfo) handlingText?.text = handlingTime.toString() if (handlingTime.toString().isEmpty() || handlingTime.isNullOrEmpty()) { handlingText?.text = "1" } Log.d("handlingTime",handlingTime.toString()) } catch (e: Exception) { Log.e("PhotosFragment", "Error parsing JSON response: ${e.message}") } }, { error -> Log.e("PhotosFragment", "Error fetching photos: ${error.message}") } ) requestQueue.add(jsonProductObjectRequest) } private fun fetchShippingDetails(){ val apiUrl = "https://websucheth.wl.r.appspot.com/getSingleData?itemId=$itemId" val jsonObjectRequest = JsonObjectRequest( Request.Method.GET, apiUrl, null, Response.Listener { response -> val itemObject = response.optJSONObject("Item") val globalShipping = itemObject?.optBoolean("GlobalShipping", false) Log.d("global",globalShipping.toString()) val globalShippingInfoB = view?.findViewById<TextView>(R.id.globalShippingInfo) if(globalShipping.toString()=="true"){ globalShippingInfoB?.text = "Yes" }else{ globalShippingInfoB?.text = "No" } val returnPolicyObject = response.optJSONObject("Item")?.optJSONObject("ReturnPolicy") val internationalReturnsAccepted = returnPolicyObject?.optString("InternationalReturnsAccepted", "") val refund = returnPolicyObject?.optString("Refund", "") val returnsAccepted = returnPolicyObject?.optString("ReturnsAccepted", "") Log.d("returnAccepted",returnsAccepted.toString()) val returnsWithin = returnPolicyObject?.optString("ReturnsWithin", "30 Days") Log.d("returnsWithing",returnsWithin.toString()) val shippingCostPaidBy = returnPolicyObject?.optString("ShippingCostPaidBy", "Seller") var policy = view?.findViewById<TextView>(R.id.policyInfo) if(returnsAccepted.toString().length>0){ policy?.text = returnsAccepted.toString() }else{ policy?.text="Returns Accepted" } Log.d("ReturnsAccepted", returnsAccepted ?: "ReturnsAccepted is null or empty") var returnsWithinText = view?.findViewById<TextView>(R.id.returnsWithinText) returnsWithinText?.text = returnsWithin.toString() var refundModes = view?.findViewById<TextView>(R.id.refundMode) refundModes?.text = refund.toString() if(refund.toString()==""){ refundModes?.text = "Money back or repl.." } var shippedby = view?.findViewById<TextView>(R.id.shippedSeller) shippedby?.text = shippingCostPaidBy.toString() if(shippingCostPaidBy.toString()==""){ shippedby?.text="Seller" } Log.d("ShippingCostBy",shippingCostPaidBy.toString()) }, Response.ErrorListener { error -> Log.e("PhotosFragment", "Error fetching photos: ${error.message}") } ) requestQueue.add(jsonObjectRequest) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate the layout for this fragment val view = inflater.inflate(R.layout.fragment_shipping, container, false) wishlistButton = view.findViewById(R.id.fab) wishlistButton.setOnClickListener { toggleWishlistItem() } return view // Return the initialized view } private fun updateWishlistButtonBackground(isInWishlist: Boolean) { // Update the background of the button based on the wishlist status val drawableResource = if (isInWishlist) R.drawable.cart_remove else R.drawable.cart_plus wishlistButton.setImageResource(drawableResource) } private fun toggleWishlistItem() { val isInWishlist = WishlistManager.isItemInWishlist(product) if (isInWishlist) { WishlistManager.removeFromWishlistInApi(requireContext(), product.itemId) Toast.makeText(requireContext(), "${product.title} was removed from the wishlist",Toast.LENGTH_SHORT ).show() updateWishlistButtonBackground(WishlistManager.isItemInWishlist(product)) } else { WishlistManager.addItemToWishlist(product) Toast.makeText(requireContext(), "${product.title} was added to the wishlist",Toast.LENGTH_SHORT ).show() updateWishlistButtonBackground(WishlistManager.isItemInWishlist(product)) } updateWishlistButtonBackground(WishlistManager.isItemInWishlist(product)) } }
Ebay-Android-APP/app/src/main/java/com/example/ebayhw4/ShippingFragment.kt
367966115
package com.example.ebayhw4 import android.content.Context import android.util.Log import androidx.lifecycle.MutableLiveData import com.android.volley.Request import com.android.volley.RequestQueue import com.android.volley.toolbox.JsonArrayRequest import com.android.volley.toolbox.JsonObjectRequest import com.android.volley.toolbox.Volley import org.json.JSONArray import org.json.JSONException import org.json.JSONObject data class WishlistItem( val itemId: String, val title: String, val galleryUrl: String, val price: String, val shippingPrice: String, val zipCode: String, val shippingInfo: JSONObject, // Change to List or Array val returnsAccepted: Boolean ) object WishlistManager { val wishlistLiveData = MutableLiveData<List<WishlistItem>>() private val wishlist: MutableList<WishlistItem> = mutableListOf() private var requestQueue: RequestQueue? = null fun init(context: Context) { requestQueue = Volley.newRequestQueue(context.applicationContext) getAllWishlistItemsFromApi() } fun addItemToWishlist(searchResultItem: SearchResultItem) { if (!isItemInWishlist(searchResultItem)) { try { val shippingInfoList = JSONObject(mapOf("shippingCondition" to searchResultItem.shippingCondition)) val wishlistItem = WishlistItem( itemId = searchResultItem.itemId, title = searchResultItem.title, galleryUrl = searchResultItem.galleryUrl, price = searchResultItem.price, shippingPrice = searchResultItem.shippingPrice, zipCode = searchResultItem.zipCode, shippingInfo = shippingInfoList, returnsAccepted = true ) addToWishlistApiCall(wishlistItem) wishlist.add(wishlistItem) wishlistLiveData.postValue(wishlist) } catch (e: JSONException) { e.printStackTrace() } } } private fun addToWishlistApiCall( wishlistItem: WishlistItem) { val fullUrl = "https://web-tech-hw-3.wl.r.appspot.com/products?itemId=${wishlistItem.itemId}&title=${wishlistItem.title}&galleryUrl=${wishlistItem.galleryUrl}&price=${wishlistItem.price}&shippingPrice=${wishlistItem.shippingPrice}&zipCode=${wishlistItem.zipCode}&shippingInfo=${wishlistItem.shippingInfo}&returnsAccepted=${wishlistItem.returnsAccepted}" Log.d("fullUrl",fullUrl) val jsonObjectRequest = JsonObjectRequest( Request.Method.GET, fullUrl, null, { response -> Log.d("API response", response.toString()) }, { error -> Log.e("Push error", error.toString()) } ) requestQueue?.add(jsonObjectRequest) getAllWishlistItemsFromApi() } fun getAllWishlistItemsFromApi() { val apiUrl = "https://web-tech-hw-3.wl.r.appspot.com/all-products" val jsonObjectRequest = JsonArrayRequest( Request.Method.GET, apiUrl, null, { response -> val wishlistItems = parseWishlistItems(response) Log.d("live data",wishlistItems.toString()) wishlistLiveData.postValue(wishlistItems) }, { error -> Log.e("Get error", error.toString()) // completion(null) } ) // Add the request to the RequestQueue requestQueue?.add(jsonObjectRequest) } fun parseWishlistItems(response: JSONArray): List<WishlistItem> { val wishlistItems = mutableListOf<WishlistItem>() try { for (i in 0 until response.length()) { val productObject = response.getJSONObject(i) val shippingInfoObject = productObject.optJSONObject("shippingInfo") ?: JSONObject() val wishlistItem = WishlistItem( itemId = productObject.getString("itemId"), title = productObject.getString("title"), galleryUrl = productObject.getString("galleryURL"), price = productObject.getString("price"), shippingPrice = productObject.getString("shippingPrice"), zipCode = productObject.getString("zipCode"), shippingInfo = shippingInfoObject, returnsAccepted = productObject.getBoolean("returnsAccepted") ) wishlistItems.add(wishlistItem) } // Update the local wishlist list with the parsed items wishlist.clear() wishlist.addAll(wishlistItems) } catch (e: JSONException) { e.printStackTrace() } return wishlistItems } fun getWishlist(): List<WishlistItem> { return wishlist } fun removeWishlistItem(context: Context, item: WishlistItem) { removeItemFromWishlist(item) removeFromWishlistInApi(context, item.itemId) } fun removeItemFromWishlist(item: WishlistItem) { wishlist.remove(item) wishlistLiveData.postValue(wishlist) } fun isItemInWishlist(searchResultItem: SearchResultItem?): Boolean { return searchResultItem != null && wishlist.any { it.itemId == searchResultItem.itemId } } fun removeFromWishlistInApi(context: Context, itemId: String) { // Instantiate the RequestQueue val requestQueue: RequestQueue = Volley.newRequestQueue(context) // Formulate the request URL val url = "https://web-tech-hw-3.wl.r.appspot.com/products/$itemId" // Create a DELETE request val request = JsonObjectRequest( Request.Method.DELETE, url, null, { response -> // Handle successful API response Log.d("API", "Item removed successfully") }, { error -> // Handle unsuccessful API response Log.e("API", "Failed to remove item from API: ${error.networkResponse?.statusCode}") } ) // Add the request to the RequestQueue requestQueue.add(request) } }
Ebay-Android-APP/app/src/main/java/com/example/ebayhw4/WishlistManager.kt
3878570531
package com.example.ebayhw4 import android.annotation.SuppressLint import android.content.Context import android.content.Intent import android.content.pm.PackageManager import android.location.Address import android.location.Geocoder import android.location.Location import android.location.LocationListener import android.location.LocationManager import android.os.AsyncTask import android.os.Build import android.os.Bundle import android.os.CountDownTimer import android.text.Editable import android.text.TextWatcher import android.util.Log import android.view.View import android.widget.AdapterView import android.widget.ArrayAdapter import android.widget.AutoCompleteTextView import android.widget.Button import android.widget.CheckBox import android.widget.EditText import android.widget.LinearLayout import android.widget.RadioButton import android.widget.Spinner import android.widget.TextView import android.widget.Toast import androidx.cardview.widget.CardView import androidx.core.app.ActivityCompat import androidx.fragment.app.Fragment import com.android.volley.Request import com.android.volley.RequestQueue import com.android.volley.Response import com.android.volley.toolbox.StringRequest import com.android.volley.toolbox.Volley import com.google.gson.Gson import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import org.json.JSONException import org.json.JSONObject import java.io.BufferedReader import java.io.IOException import java.io.InputStreamReader import java.net.HttpURLConnection import java.net.URL import java.util.Locale class ApiCallTask(private val listener: ApiCallListener) : AsyncTask<String, Void, String>() { private var apiResult: String = "" override fun doInBackground(vararg params: String): String { try { val url = URL(params[0]) val connection: HttpURLConnection = url.openConnection() as HttpURLConnection connection.requestMethod = "GET" val bufferedReader = BufferedReader(InputStreamReader(connection.inputStream)) apiResult = bufferedReader.use { it.readText() } } catch (e: Exception) { Log.d("errorclick7","click") e.printStackTrace() } return apiResult } override fun onPostExecute(result: String) { // Store the result apiResult = result // Notify the listener listener.onApiCallComplete(apiResult) } // Add a method to get the stored result fun getApiResult(): String { return apiResult } } interface ApiCallListener { fun onApiCallComplete(result: String) } data class SearchParameters( val keyword: String, val category: String, val new: Boolean, val used: Boolean, val unspecified: Boolean, val local: Boolean, val freeshipping: Boolean, val distance: Int, val location: String, val zipCode: Any? ) class SearchFragment : Fragment(R.layout.fragment_search) { private lateinit var autoSuggestAdapter: AutoSuggestAdapter private lateinit var requestQueue: RequestQueue private lateinit var spinner: Spinner private lateinit var locationManager: LocationManager private lateinit var locationListener: LocationListener private var currentLocation: Location? = null private var currentZipCode: String? = null private var liveLocation: String? = null private val MIN_TIME_BETWEEN_UPDATES = 1000L // 1 second private val MIN_DISTANCE_CHANGE_FOR_UPDATES = 1f private var editTextZipCode: AutoCompleteTextView? = null val categories = arrayOf( "All", "Art", "Baby", "Books", "Clothing,Shoes and Accessories", "Computer, Tablets and Network", "Health and Beauty", "Music", "Video, Games and Consoles" ) @SuppressLint("SuspiciousIndentation") override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) // Find the Spinner in the layout spinner = view.findViewById(R.id.spinner) val radioButtonCurrentLocation = view.findViewById<RadioButton>(R.id.radioButtonCurrentLocation) val radioButtonZipCode = view.findViewById<RadioButton>(R.id.radioButton3) radioButtonCurrentLocation.isChecked = true getLocation() radioButtonCurrentLocation.setOnClickListener { view?.post { radioButtonCurrentLocation.isChecked = true } radioButtonZipCode.isChecked = false } val editTextZipCode = view.findViewById<AutoCompleteTextView>(R.id.editTextText4) autoSuggestAdapter = AutoSuggestAdapter(requireContext(), android.R.layout.simple_dropdown_item_1line) editTextZipCode?.setAdapter(autoSuggestAdapter) setupZipCodeAutoComplete() radioButtonZipCode.setOnClickListener { radioButtonCurrentLocation.isChecked = false radioButtonZipCode.isChecked = true makeZipCodeRequest(editTextZipCode.text.toString(), editTextZipCode) } val checkBox: CheckBox = view.findViewById(R.id.checkBox13) val layout = view.findViewById<LinearLayout>(R.id.myLinearLayout) val searchButton = view.findViewById<Button>(R.id.searchButton) val clearButton = view.findViewById<Button>(R.id.clearButton) clearButton.setOnClickListener { clearForm() } val editTextKeyword = view.findViewById<EditText>(R.id.editTextText) val textView8 = view.findViewById<TextView>(R.id.textView8) layout.visibility = if (checkBox.isChecked) View.VISIBLE else View.GONE checkBox.setOnCheckedChangeListener { _, isChecked -> layout.visibility = if (isChecked) View.VISIBLE else View.GONE } // Create an ArrayAdapter using the string array and a default spinner layout val adapter: ArrayAdapter<String> = ArrayAdapter(requireContext(), android.R.layout.simple_spinner_item, categories) // Specify the layout to use when the list of choices appears adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item) // Apply the adapter to the spinner spinner.adapter = adapter // Set up a listener for spinner item selection spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener { override fun onItemSelected( parent: AdapterView<*>?, view: View?, position: Int, id: Long ) { // Handle the selected item (category) here val selectedCategory = categories[position] // You can perform actions based on the selected category } override fun onNothingSelected(parent: AdapterView<*>?) { // Do nothing here, optional implementation } } searchButton.setOnClickListener { val warning = view?.findViewById<TextView>(R.id.warning) val keyword = editTextKeyword?.text.toString().trim() val currentRadioButton = view?.findViewById<RadioButton>(R.id.radioButtonCurrentLocation) val zipRadioButton = view?.findViewById<RadioButton>(R.id.radioButton3) val zip = editTextZipCode?.text.toString().trim() // Check if either keyword or zip code is empty if (zipRadioButton != null) { if(zipRadioButton.isChecked().toString()=="true"){ if (zip.isEmpty() && keyword.isEmpty()) { warning?.visibility = View.VISIBLE textView8?.visibility = View.VISIBLE Toast.makeText( requireContext(), "Please fix all fields with errors", Toast.LENGTH_SHORT ).show() } else if (zip.isEmpty()) { warning?.visibility = View.VISIBLE Toast.makeText( requireContext(), "Please fix all fields with errors", Toast.LENGTH_SHORT ).show() } } } if (keyword.isEmpty()) { textView8?.visibility = View.VISIBLE Toast.makeText( requireContext(), "Please fix all fields with errors", Toast.LENGTH_SHORT ).show() } else { warning?.visibility = View.GONE textView8?.visibility = View.GONE // Continue with the search // ... (rest of the method) onSearchButtonClick(keyword) } } } private fun getLocation() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { if (ActivityCompat.checkSelfPermission( requireContext(), android.Manifest.permission.ACCESS_FINE_LOCATION ) == PackageManager.PERMISSION_GRANTED ) { getCurrentLocation() } else { requestPermissions(arrayOf(android.Manifest.permission.ACCESS_FINE_LOCATION), 1) } } else { getCurrentLocation() } } private fun getCurrentLocation() { locationManager = requireActivity().getSystemService(Context.LOCATION_SERVICE) as LocationManager locationListener = object : LocationListener { override fun onLocationChanged(location: Location) { try { val geocoder = Geocoder(requireContext(), Locale.getDefault()) val addresses: List<Address>? = geocoder.getFromLocation(location.latitude, location.longitude, 1) if (addresses != null && addresses.isNotEmpty()) { currentZipCode = addresses[0]?.postalCode } } catch (e: IOException) { Log.d("errorclick8","click") e.printStackTrace() } // Remove updates only when necessary locationManager.removeUpdates(this) } override fun onStatusChanged(provider: String?, status: Int, extras: Bundle?) { } override fun onProviderEnabled(provider: String) { } override fun onProviderDisabled(provider: String) { } } try { // Request location updates with GPS_PROVIDER for accuracy locationManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, MIN_TIME_BETWEEN_UPDATES, // Minimum time interval between updates (adjust as needed) MIN_DISTANCE_CHANGE_FOR_UPDATES, // Minimum distance between updates (adjust as needed) locationListener ) } catch (e: SecurityException) { Log.d("errorclick9","click") e.printStackTrace() } } // Inside the clearForm function private fun clearForm() { val editTextKeyword = view?.findViewById<EditText>(R.id.editTextText) editTextKeyword?.text?.clear() val textView8 = view?.findViewById<TextView>(R.id.textView8) textView8?.visibility = View.GONE val warning = view?.findViewById<TextView>(R.id.warning) warning?.visibility = View.GONE // Correctly reference the RadioButton val radioButtonCurrentLocation = view?.findViewById<RadioButton>(R.id.radioButtonCurrentLocation) radioButtonCurrentLocation?.isChecked = true // Set the spinner to the first item ("All") val spinner = view?.findViewById<Spinner>(R.id.spinner) spinner?.setSelection(0) // Uncheck all checkboxes val checkBoxNew = view?.findViewById<CheckBox>(R.id.checkBox7) checkBoxNew?.isChecked = false val checkBoxUsed = view?.findViewById<CheckBox>(R.id.checkBox8) checkBoxUsed?.isChecked = false val checkBoxUnspecified = view?.findViewById<CheckBox>(R.id.checkBox9) checkBoxUnspecified?.isChecked = false val checkBoxLocal = view?.findViewById<CheckBox>(R.id.checkBox11) checkBoxLocal?.isChecked = false val checkBoxFreeShipping = view?.findViewById<CheckBox>(R.id.checkBox12) checkBoxFreeShipping?.isChecked = false val enableNearBySearch = view?.findViewById<CheckBox>(R.id.checkBox13) enableNearBySearch?.isChecked = false // Set visibility of the layout to GONE val layout = view?.findViewById<LinearLayout>(R.id.myLinearLayout) layout?.visibility = View.GONE // Clear the distance EditText val editTextDistance = view?.findViewById<EditText>(R.id.editTextText2) editTextDistance?.text?.clear() // Uncheck the radio buttons val radioButtonZipCode = view?.findViewById<RadioButton>(R.id.radioButton3) radioButtonZipCode?.isChecked = false // Clear the zip code EditText editTextZipCode = view?.findViewById<AutoCompleteTextView>(R.id.editTextText4) editTextZipCode?.text?.clear() } private fun updateUI(apiResult: String) { try { // Parse the JSON response and update your UI val gson = Gson() val searchParameters = gson.fromJson(apiResult, SearchParameters::class.java) // Check if searchParameters is not null before accessing its properties if (searchParameters != null) { val keyword = searchParameters.keyword // Do whatever you need with the keyword or other properties } else { Log.e("SearchResults", "SearchParameters object is null") } } catch (e: Exception) { Log.d("errorclick10","click") Log.e("SearchResults", "Error updating UI", e) } } private fun onSearchButtonClick(keyword: String) { try { Log.d("tryclick","click") val editTextKeyword = view?.findViewById<EditText>(R.id.editTextText) val keyword = editTextKeyword?.text.toString().trim() val spinner = view?.findViewById<Spinner>(R.id.spinner) val selectedCategory = categories[spinner?.selectedItemPosition ?: 0] val checkBoxNew = view?.findViewById<CheckBox>(R.id.checkBox7) val newChecked = checkBoxNew?.isChecked ?: false val checkBoxUsed = view?.findViewById<CheckBox>(R.id.checkBox8) val usedChecked = checkBoxUsed?.isChecked ?: false val checkBoxUnspecified = view?.findViewById<CheckBox>(R.id.checkBox9) val unspecifiedChecked = checkBoxUnspecified?.isChecked ?: false val checkBoxLocal = view?.findViewById<CheckBox>(R.id.checkBox11) val localChecked = checkBoxLocal?.isChecked ?: false val checkBoxFreeShipping = view?.findViewById<CheckBox>(R.id.checkBox12) val freeShippingChecked = checkBoxFreeShipping?.isChecked ?: false val editTextDistance = view?.findViewById<EditText>(R.id.editTextText2) val distance = editTextDistance?.text.toString().toIntOrNull() ?: 10 val radioButtonCurrentLocation = view?.findViewById<RadioButton>(R.id.radioButtonCurrentLocation) val radioButtonZipCode = view?.findViewById<RadioButton>(R.id.radioButton3) val editTextZipCode = view?.findViewById<EditText>(R.id.editTextText4) val zipCode = if (editTextZipCode?.text.toString().length > 0) editTextZipCode?.text.toString() else currentZipCode // Create SearchParameters instance val searchParams = SearchParameters( keyword = keyword, category = if (selectedCategory == "All") "All Categories" else selectedCategory, new = newChecked, used = usedChecked, unspecified = unspecifiedChecked, local = localChecked, freeshipping = freeShippingChecked, distance = distance, location = if (radioButtonCurrentLocation?.isChecked == true) "current" else "zip", zipCode = zipCode.toString() ) // Convert to JSON using Gson val searchParamsJson = Gson().toJson(searchParams) // Construct the API URL val apiUrl = "https://web-tech-hw-3.wl.r.appspot.com/search-results?searchParams=$searchParamsJson" val splashIntent = Intent(requireContext(), LoadScreen::class.java) // Put the search parameters as extras to the intent splashIntent.putExtra("Search_PARAMS", searchParamsJson) // Start the SplashActivity startActivity(splashIntent) } catch (e: Exception) { Log.d("errorclick","click") Log.e("SearchFragment", "Error during search button click", e) } } class ApiCallTask(private val listener: ApiCallListener) { fun execute(apiUrl: String) { GlobalScope.launch(Dispatchers.IO) { try { val result = makeApiCall(apiUrl) withContext(Dispatchers.Main) { listener.onApiCallComplete(result) } } catch (e: Exception) { Log.d("errorclick2","click") e.printStackTrace() } } } private fun makeApiCall(apiUrl: String): String { val url = URL(apiUrl) val connection: HttpURLConnection = url.openConnection() as HttpURLConnection connection.requestMethod = "GET" val bufferedReader = BufferedReader(InputStreamReader(connection.inputStream)) return bufferedReader.use { it.readText() } } } private fun getCurrentLocationZipCode(): String { return try { val geocoder = Geocoder(requireContext(), Locale.getDefault()) val addresses: List<Address>? = geocoder.getFromLocation( currentLocation?.latitude ?: 0.0, currentLocation?.longitude ?: 0.0, 1 ) if (addresses != null && addresses.isNotEmpty()) { addresses[0]?.postalCode ?: "" } else { "" } } catch (e: IOException) { Log.d("errorclick5","click") e.printStackTrace() "" } } private fun setupZipCodeAutoComplete() { val autoCompleteZipCode = view?.findViewById<AutoCompleteTextView>(R.id.editTextText4) autoCompleteZipCode?.addTextChangedListener(object : TextWatcher { private var debounceTimer: CountDownTimer? = null override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) { debounceTimer?.cancel() } override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { // Cancel the previous timer debounceTimer?.cancel() // Set up a new timer to wait for the user to finish typing debounceTimer = object : CountDownTimer(500, 500) { override fun onTick(millisUntilFinished: Long) {} override fun onFinish() { // Make the API call to get suggestions Log.d("string",s.toString()) makeZipCodeRequest(s.toString(), autoCompleteZipCode) } }.start() } override fun afterTextChanged(s: Editable?) {} }) autoCompleteZipCode?.onItemClickListener = AdapterView.OnItemClickListener { parent, _, position, _ -> // Handle item click here if needed val selectedItem = parent.getItemAtPosition(position) as String Toast.makeText( requireContext(), "Selected Zip Code: $selectedItem", Toast.LENGTH_SHORT ).show() } } private fun makeZipCodeRequest(zipCode: String, autoCompleteTextView: AutoCompleteTextView) { val url = "https://web-tech-hw-3.wl.r.appspot.com/zip-suggestions?zipCode=$zipCode" val stringRequest = StringRequest( Request.Method.GET, url, Response.Listener<String> { response -> // Parse the JSON object view?.findViewById<LinearLayout>(R.id.linearLayout2)?.visibility = View.GONE view?.findViewById<CardView>(R.id.wishlistCardView)?.visibility = View.GONE view?.findViewById<TextView>(R.id.noItemsTextView)?.visibility = View.GONE val zipCodeList = mutableListOf<String>() try { // Parse the response and extract ZIP codes val jsonObject = JSONObject(response) val postalCodesArray = jsonObject.getJSONArray("postalCodes") for (i in 0 until postalCodesArray.length()) { val postalCodeObject = postalCodesArray.getJSONObject(i) zipCodeList.add(postalCodeObject.getString("postalCode")) } } catch (e: JSONException) { Log.d("errorclick6","click") e.printStackTrace() } // Extract the "postalCodes" array // Use postalCodeList as needed, for example, setting it to the AutoCompleteTextView val adapter = ArrayAdapter( requireContext(), android.R.layout.simple_dropdown_item_1line, zipCodeList ) autoCompleteTextView.setAdapter(adapter) autoCompleteTextView.showDropDown() }, Response.ErrorListener { error -> Log.e("Volley", "Error: $error") } ) Volley.newRequestQueue(requireContext()).add(stringRequest) } }
Ebay-Android-APP/app/src/main/java/com/example/ebayhw4/SearchFragment.kt
4052561166
package com.example.ebayhw4 import SearchResultsAdapter import android.os.Bundle import android.os.Parcel import android.os.Parcelable import android.util.Log import android.view.MenuItem import android.view.View import android.widget.LinearLayout import android.widget.TextView import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.widget.Toolbar import androidx.cardview.widget.CardView import androidx.core.app.NavUtils import androidx.core.app.TaskStackBuilder import androidx.recyclerview.widget.GridLayoutManager import androidx.recyclerview.widget.RecyclerView import com.android.volley.Request import com.android.volley.RequestQueue import com.android.volley.Response import com.android.volley.toolbox.StringRequest import com.android.volley.toolbox.Volley import org.json.JSONException import org.json.JSONObject data class SearchResultItem( val itemId: String, val title: String, val galleryUrl: String, val price: String, val shippingPrice: String, val zipCode: String, val shippingCondition: String ) : Parcelable { constructor(parcel: Parcel) : this( parcel.readString() ?: "", parcel.readString() ?: "", parcel.readString() ?: "", parcel.readString() ?: "", parcel.readString() ?: "", parcel.readString() ?: "", parcel.readString() ?: "" ) override fun writeToParcel(parcel: Parcel, flags: Int) { parcel.writeString(itemId) parcel.writeString(title) parcel.writeString(galleryUrl) parcel.writeString(price) parcel.writeString(shippingPrice) parcel.writeString(zipCode) parcel.writeString(shippingCondition) } override fun describeContents(): Int { return 0 } companion object CREATOR : Parcelable.Creator<SearchResultItem> { override fun createFromParcel(parcel: Parcel): SearchResultItem { return SearchResultItem(parcel) } override fun newArray(size: Int): Array<SearchResultItem?> { return arrayOfNulls(size) } } } class SearchResults : AppCompatActivity() { private var mRequestQueue: RequestQueue? = null private var url: String? = null private lateinit var recyclerView: RecyclerView private lateinit var adapter: SearchResultsAdapter private var count: Number? = null private var resultsList = mutableListOf<SearchResultItem>() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_search_results) val toolbar: Toolbar = findViewById(R.id.toolbar) setSupportActionBar(toolbar) // Enable the back arrow in the toolbar supportActionBar?.setDisplayHomeAsUpEnabled(true) // Retrieve the SearchParameters JSON from the intent val searchParamsJson = intent.getStringExtra("Search_PARAMS") url = "https://web-tech-hw-3.wl.r.appspot.com/search-results?searchParams=$searchParamsJson" mRequestQueue = Volley.newRequestQueue(this) recyclerView = findViewById(R.id.recyclerView) recyclerView.layoutManager = GridLayoutManager(this, 2) // Set the number of columns adapter = SearchResultsAdapter(resultsList,searchParamsJson) recyclerView.adapter = adapter // String Request initialized val stringRequest = StringRequest(Request.Method.GET, url, Response.Listener { response -> // Display the response on screen or handle it as needed parseApiResponse(response) }, Response.ErrorListener { error -> // Handle errors Log.e("ApiError", "Error: ${error.toString()}") Toast.makeText(applicationContext, "Error: ${error.toString()}", Toast.LENGTH_LONG).show() }) mRequestQueue?.add(stringRequest) } private fun parseApiResponse(response: String) { resultsList.clear() val result = JSONObject(response) try { // Assuming result is a JSONArray val resultArray = result.getJSONArray("searchResult") // Access the first item in the array val firstItem = resultArray.getJSONObject(0) // Access the value of @count val countValue = firstItem.getString("@count") count = countValue.toInt() } catch (e: JSONException) { e.printStackTrace() } try { if(response.isNullOrEmpty()){ var ll = findViewById<LinearLayout>(R.id.linearLayout2) ll.visibility = View.VISIBLE val cardView = findViewById<CardView>(R.id.wishlistCardView) cardView.visibility = View.VISIBLE val tt = findViewById<TextView>(R.id.noItemsTextView) tt.visibility = View.VISIBLE } val jsonObject = JSONObject(response) val searchResultArray = jsonObject.getJSONArray("searchResult") for (i in 0 until searchResultArray.length()) { val searchResultItem = searchResultArray.getJSONObject(i) // Extract @count and item array from each search result item val countValue = searchResultItem.getString("@count") val itemArray = searchResultItem.getJSONArray("item") // Iterate through the item array for (j in 0 until itemArray.length()) { val itemObject = itemArray.getJSONObject(j) val shippingCost = itemObject.getJSONArray("shippingInfo").getJSONObject(0) .getJSONArray("shippingServiceCost").getJSONObject(0).getString("__value__") ?: "N/A" val rawTitle = itemObject.getJSONArray("title").getString(0) ?: "N/A" val truncatedTitle = if (rawTitle.length > 30) { "${rawTitle.substring(0, 30)}..." } else { rawTitle } var condition = itemObject.getJSONArray("condition").getJSONObject(0).getJSONArray("conditionDisplayName")[0].toString() val currentItem = SearchResultItem( itemId = itemObject.getJSONArray("itemId").getString(0) ?: "N/A", title = truncatedTitle, galleryUrl = itemObject.getJSONArray("galleryURL").getString(0) ?: "N/A", price = itemObject.getJSONArray("sellingStatus").getJSONObject(0).getJSONArray("currentPrice").getJSONObject(0).get("__value__").toString(), shippingPrice = if (shippingCost == "0.0") "Free" else shippingCost, zipCode = (itemObject.getJSONArray("postalCode").getString(0) ?: "N/A"), shippingCondition = condition, ) WishlistManager.init(applicationContext) resultsList.add(currentItem) } } } catch (e: Exception) { e.printStackTrace() Log.e("JsonParsingError", "Error parsing JSON: ${e.message}") } adapter.notifyDataSetChanged() } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { android.R.id.home -> { navigateUpToMain() return true } } return super.onOptionsItemSelected(item) } private fun navigateUpToMain() { // Create an Intent to navigate up to the parent activity (SearchFragment) val upIntent = NavUtils.getParentActivityIntent(this) // If upIntent is not null and the activity is not in the back stack, create a new task if (upIntent != null && NavUtils.shouldUpRecreateTask(this, upIntent)) { TaskStackBuilder.create(this) .addNextIntentWithParentStack(upIntent) .startActivities() } else { // If the activity is in the back stack, simply navigate up if (upIntent != null) { NavUtils.navigateUpTo(this, upIntent) } } } }
Ebay-Android-APP/app/src/main/java/com/example/ebayhw4/SearchResults.kt
2495294701
package com.example.ebayhw4 import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView class WishList : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_wish_list) val recyclerView: RecyclerView = findViewById(R.id.recyclerView) val wishlistItems: MutableList<WishlistItem> = WishlistManager.getWishlist().toMutableList() val adapter = WishlistAdapter(wishlistItems) recyclerView.adapter = adapter recyclerView.layoutManager = LinearLayoutManager(this) } }
Ebay-Android-APP/app/src/main/java/com/example/ebayhw4/WishList.kt
1505765640
package com.example.ebayhw4 import PhotosFragment import ProductFragment import android.content.Intent import android.net.Uri import android.os.Bundle import android.os.Handler import android.util.Log import android.view.MenuItem import android.view.View import android.widget.ImageButton import android.widget.ProgressBar import android.widget.TextView import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.widget.Toolbar import androidx.fragment.app.Fragment import androidx.fragment.app.FragmentManager import androidx.fragment.app.FragmentPagerAdapter import androidx.recyclerview.widget.RecyclerView import androidx.viewpager.widget.ViewPager import com.android.volley.Request import com.android.volley.RequestQueue import com.android.volley.Response import com.android.volley.toolbox.JsonObjectRequest import com.android.volley.toolbox.Volley import com.google.android.material.tabs.TabLayout import org.json.JSONObject class itemDetailsSplash : AppCompatActivity() { private lateinit var itemId: String private lateinit var progressBar: ProgressBar private lateinit var titleTextView: TextView private lateinit var viewPager: ViewPager private lateinit var tabLayout: TabLayout private lateinit var requestQueue: RequestQueue private lateinit var item: JSONObject private lateinit var viewItemURL: String private lateinit var title: String private lateinit var convertedCurrentPrice: JSONObject private lateinit var currency: String private lateinit var searchParamsJson: String private lateinit var shippingCost:String private var convertedPrice: Double = 0.0 override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_item_details_splash) val toolbar: Toolbar = findViewById(R.id.toolbar) setSupportActionBar(toolbar) var product = intent.getParcelableExtra<SearchResultItem>("product") supportActionBar?.setDisplayHomeAsUpEnabled(true) progressBar = findViewById(R.id.progressBar) titleTextView = findViewById(R.id.textView4) itemId = intent.getStringExtra("productId") ?: "" searchParamsJson = intent.getStringExtra("searchParams") ?: "" shippingCost = intent.getStringExtra("shippingCost").toString() val position = intent.getIntExtra("position", RecyclerView.NO_POSITION) val facebookButton = findViewById<ImageButton>(R.id.facebookButton) facebookButton.setOnClickListener { shareOnFacebook() } titleTextView.text = "Fetching Product Details ..." var titleText = findViewById<TextView>(R.id.titleText) titleText.text = intent.getStringExtra("title")?:"" viewPager = findViewById(R.id.viewPager) searchParamsJson = intent.getStringExtra("searchParams") ?: "" tabLayout = findViewById(R.id.tabLayout) val adapter = TabPagerAdapter(supportFragmentManager,itemId,searchParamsJson,shippingCost,product,position) viewPager.adapter = adapter // Link the TabLayout to the ViewPager tabLayout.setupWithViewPager(viewPager) adapter.setupTabIcons() requestQueue = Volley.newRequestQueue(this) makeApiCall() Handler().postDelayed( { progressBar.visibility = View.GONE titleTextView.visibility = View.GONE viewPager.visibility = View.VISIBLE }, getSplashScreenDuration() ) } private inner class TabPagerAdapter(fm: FragmentManager, private val itemId: String, private val searchParamsJson: String, private val shippingCost: String, private val product: SearchResultItem?, private val location: Int) : FragmentPagerAdapter(fm) { private val tabTitles = arrayOf("Product", "Shipping", "Photos", "Similar") private val tabIcons = intArrayOf(R.drawable.information_variant, R.drawable.truck_delivery, R.drawable.google, R.drawable.equal) override fun getItem(position: Int): Fragment { return when (position) { 0 -> ProductFragment.newInstance(itemId,shippingCost, product) 1 -> ShippingFragment.newInstance(itemId, searchParamsJson, shippingCost,product,location) 2 -> PhotosFragment.newInstance(title,product) 3 -> SimilarFragment.newInstance(itemId,product) else -> throw IllegalArgumentException("Invalid position: $position") } } override fun getCount(): Int { return tabTitles.size // Number of tabs } override fun getPageTitle(position: Int): CharSequence? { return tabTitles[position] } fun setupTabIcons() { for (i in 0 until tabIcons.size) { val tab = tabLayout.getTabAt(i) tab?.setIcon(tabIcons[i]) } } } private fun shareOnFacebook() { // Create a Facebook sharing URL val hashtag = Uri.encode("#CSCI571Fall23AndroidApp") val facebookUrl = "https://www.facebook.com/sharer/sharer.php?u=$viewItemURL"+"&amp;src=sdkpreparse&hashtag=$hashtag" // Open the Facebook sharing page in a web browser val intent = Intent(Intent.ACTION_VIEW, Uri.parse(facebookUrl)) startActivity(intent) } private fun makeApiCall() { // Use the itemId obtained from arguments val url = "https://web-tech-hw-3.wl.r.appspot.com/product-details?itemId=$itemId" // Create a request using the JsonObjectRequest class val jsonObjectRequest = JsonObjectRequest( Request.Method.GET, url, null, Response.Listener { response -> item = response.getJSONObject("Item") viewItemURL = item.getString("ViewItemURLForNaturalSearch") title = item.getString("Title") convertedCurrentPrice = item.getJSONObject("ConvertedCurrentPrice") currency = convertedCurrentPrice.getString("CurrencyID") convertedPrice = convertedCurrentPrice.getDouble("Value") // Now you can use viewItemURL, title, and convertedPrice in your application }, Response.ErrorListener { error -> // Handle errors here Log.e("error", error.toString()) } ) // Add the request to the RequestQueue requestQueue.add(jsonObjectRequest) } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { android.R.id.home -> { navigateUpToSearchResults() return true } } return super.onOptionsItemSelected(item) } private fun navigateUpToSearchResults() { // Create an Intent to navigate up to the SearchResults activity val searchResultsIntent = Intent(this, SearchResults::class.java) // Add any extras you need to pass to the SearchResults activity searchResultsIntent.putExtra("Search_PARAMS", searchParamsJson) // Navigate up to the SearchResults activity startActivity(searchResultsIntent) // Finish the current activity (itemDetailsSplash) finish() } private fun scheduleSplashScreen(searchParamsJson: String?) { val splashScreenDuration = getSplashScreenDuration() Handler().postDelayed( { // After the splash screen duration, start the SearchResults activity startSearchResultsActivity(searchParamsJson) finish() }, splashScreenDuration ) } private fun startSearchResultsActivity(searchParamsJson: String?) { // Create an Intent to start the SearchResults activity val searchResultsIntent = Intent(this, SearchResults::class.java) // Put the search parameters as extras to the intent // Start the SearchResults activity startActivity(searchResultsIntent) } private fun getSplashScreenDuration() = 2000L }
Ebay-Android-APP/app/src/main/java/com/example/ebayhw4/itemDetailsSplash.kt
1074174633
import android.os.Bundle import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageButton import android.widget.ImageView import android.widget.LinearLayout import android.widget.TextView import android.widget.Toast import androidx.fragment.app.Fragment import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.PagerSnapHelper import androidx.recyclerview.widget.RecyclerView import com.android.volley.Request import com.android.volley.RequestQueue import com.android.volley.Response import com.android.volley.toolbox.JsonObjectRequest import com.android.volley.toolbox.Volley import com.example.ebayhw4.R import com.example.ebayhw4.SearchResultItem import com.example.ebayhw4.WishlistItem import com.example.ebayhw4.WishlistManager import com.squareup.picasso.Picasso import org.json.JSONObject class ProductFragment : Fragment() { private var itemId: String? = null private lateinit var requestQueue: RequestQueue private var pictureUrls: List<String>? = null private lateinit var imageRecyclerView: RecyclerView private var title:String? = null private var currentPrice: String? = null private var shippingCost:String? = null private var brand:String?= null private lateinit var imageContainer: LinearLayout private lateinit var wishlistItem: WishlistItem companion object { fun newInstance(itemId: String, shippingCost: String, product: SearchResultItem?): ProductFragment { val fragment = ProductFragment() val args = Bundle() args.putString("itemId", itemId) args.putString("shippingCost",shippingCost) args.putParcelable("product", product) fragment.arguments = args return fragment } } private lateinit var wishlistButton:ImageButton private lateinit var product: SearchResultItem override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) itemId = arguments?.getString("itemId") shippingCost = arguments?.getString("shippingCost") product = arguments?.getParcelable("product")!! // Use the product as needed in your fragment Log.d("productFragment Product", product.toString()) Log.d("shippingCost",shippingCost.toString()) // Initialize the RequestQueue requestQueue = Volley.newRequestQueue(requireContext()) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { val view = inflater.inflate(R.layout.fragment_product, container, false) imageRecyclerView = view.findViewById(R.id.imageRecyclerView) imageRecyclerView.layoutManager = LinearLayoutManager(requireContext(), LinearLayoutManager.HORIZONTAL, false) imageRecyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() { override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) { } }) val snapHelper = PagerSnapHelper() snapHelper.attachToRecyclerView(imageRecyclerView) wishlistButton = view.findViewById(R.id.fab) wishlistButton.setOnClickListener { toggleWishlistItem() } val shippingInfoList = JSONObject(mapOf("shippingCondition" to product?.shippingCondition.orEmpty())) wishlistItem = WishlistItem( itemId = product?.itemId.orEmpty(), title = product?.title.orEmpty(), galleryUrl = product?.galleryUrl.orEmpty(), price = product?.price.orEmpty(), shippingPrice = product?.shippingPrice.orEmpty(), zipCode = product?.zipCode.orEmpty(), shippingInfo = shippingInfoList, returnsAccepted = true ) return view } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) makeApiCall() } private fun toggleWishlistItem() { val isInWishlist = WishlistManager.isItemInWishlist(product) if (isInWishlist) { WishlistManager.removeFromWishlistInApi(requireContext(),wishlistItem.itemId) Toast.makeText( requireContext(), "${product.title} was removed from the wishlist", Toast.LENGTH_SHORT ).show() } else { WishlistManager.addItemToWishlist(product) Toast.makeText( requireContext(), "${product.title} was added to the wishlist", Toast.LENGTH_SHORT ).show() } // Update the background of the button after toggling updateWishlistButtonBackground(!isInWishlist) } private fun updateWishlistButtonBackground(isInWishlist: Boolean) { // Update the background of the button based on the wishlist status val drawableResource = if (isInWishlist) R.drawable.cart_remove else R.drawable.cart_plus wishlistButton.setImageResource(drawableResource) // wishlistButton.foreground = if (isInWishlist) ContextCompat.getDrawable(requireContext(), R.drawable.orange_wishlist_removal) else ContextCompat.getDrawable(requireContext(), R.drawable.ic_launcher_wishlist_float) } private fun makeApiCall() { val url = "https://web-tech-hw-3.wl.r.appspot.com/product-details?itemId=$itemId" Log.d("url",url) val jsonObjectRequest = JsonObjectRequest( Request.Method.GET, url, null, Response.Listener { response -> pictureUrls = response.getJSONObject("Item").getJSONArray("PictureURL") ?.let { 0.until(it.length()).map { i -> it.optString(i) } } ?: emptyList() val adapter = ImageAdapter(pictureUrls!!) imageRecyclerView.adapter = adapter title = response.getJSONObject("Item").getString("Title") var titleTextView = view?.findViewById<TextView>(R.id.productTitle) titleTextView?.text = title currentPrice = response.getJSONObject("Item").getJSONObject("CurrentPrice").getString("Value") var shipCost = view?.findViewById<TextView>(R.id.priceShipping) if(shippingCost=="Free"){ shippingCost = "With Free Shipping" }else{ shippingCost = "With $"+shippingCost+" Shipping" } shipCost?.text = "$"+currentPrice.toString()+" "+shippingCost.toString() var cost = view?.findViewById<TextView>(R.id.price) cost?.text = "$"+currentPrice.toString() val itemSpecificsArray = response.getJSONObject("Item") .getJSONObject("ItemSpecifics") .getJSONArray("NameValueList") for (i in 0 until itemSpecificsArray.length()) { val nameValue = itemSpecificsArray.getJSONObject(i) val name = nameValue.getString("Name") if (name == "Brand") { val brandArray = nameValue.getJSONArray("Value") brand = if (brandArray.length() > 0) brandArray.getString(0) else null break } } var b = view?.findViewById<TextView>(R.id.brand) b?.text = brand.toString() val itemSpecificsObject = response.getJSONObject("Item").getJSONObject("ItemSpecifics") val nameValueListArray = itemSpecificsObject.getJSONArray("NameValueList") // Initialize the brand value var brandValue = "" // Dynamically add TextView for each "ItemSpecifics" value for (i in 0 until nameValueListArray.length()) { val nameValue = nameValueListArray.getJSONObject(i) val name = nameValue.optString("Name") val valueArray = nameValue.optJSONArray("Value") // Skip the row if details are missing if (name.isNullOrEmpty() || valueArray == null || valueArray.length() == 0) { continue } // Extracting and capitalizing the first letter of each value for (j in 0 until valueArray.length()) { val value = valueArray.getString(j) val capitalizedValue = value.toLowerCase().capitalize() // Set the brand value for later use if (name.equals("Brand", ignoreCase = true)) { brandValue = capitalizedValue } // Dynamically add TextView for each value addTextViewToContainer("* "+capitalizedValue) } } }, Response.ErrorListener { error -> Log.d("error",error.toString()) } ) val product: SearchResultItem? = arguments?.getParcelable("product") requestQueue.add(jsonObjectRequest) updateWishlistButtonBackground(WishlistManager.isItemInWishlist(product)) } private fun addTextViewToContainer(text: String) { val textView = TextView(requireContext()) textView.layoutParams = ViewGroup.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT ) textView.text = text view?.findViewById<LinearLayout>(R.id.specificationsContainer)?.addView(textView) } class ImageAdapter(private val pictureUrls: List<String>) : RecyclerView.Adapter<ImageAdapter.ImageViewHolder>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ImageViewHolder { val imageView = ImageView(parent.context) imageView.layoutParams = ViewGroup.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT ) imageView.scaleType = ImageView.ScaleType.FIT_XY return ImageViewHolder(imageView) } override fun onBindViewHolder(holder: ImageViewHolder, position: Int) { Picasso.get().load(pictureUrls[position]).into(holder.imageView) } override fun getItemCount(): Int { return pictureUrls.size } class ImageViewHolder(val imageView: ImageView) : RecyclerView.ViewHolder(imageView) } }
Ebay-Android-APP/app/src/main/java/com/example/ebayhw4/ProductFragment.kt
818692469
package com.example.ebayhw4 import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.ImageView class SplashActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_splash) val iv_note = findViewById<ImageView>(R.id.iv_note) iv_note.alpha=1f iv_note.animate().setDuration(1500).alpha(1f).withEndAction{ val i = Intent(this,MainActivity::class.java) startActivity(i) finish() } } }
Ebay-Android-APP/app/src/main/java/com/example/ebayhw4/SplashActivity.kt
1170115151
package com.example.ebayhw4 import android.content.Context import android.widget.ArrayAdapter import android.widget.Filter class AutoSuggestAdapter(context: Context, resource: Int) : ArrayAdapter<String>(context, resource) { private var suggestionList = mutableListOf<String>() fun setSuggestions(suggestions: List<String>) { suggestionList.clear() suggestionList.addAll(suggestions) notifyDataSetChanged() } override fun getCount(): Int { return suggestionList.size } override fun getItem(index: Int): String? { return if (index < suggestionList.size) { suggestionList[index] } else { null } } override fun getFilter(): Filter { return object : Filter() { override fun convertResultToString(resultValue: Any?): CharSequence { return resultValue as String } override fun performFiltering(constraint: CharSequence?): FilterResults { val filterResults = FilterResults() if (constraint != null) { // Perform API call or any other logic to get suggestions based on the constraint // For simplicity, we'll just return the entire list for demonstration purposes filterResults.values = suggestionList filterResults.count = suggestionList.size } return filterResults } override fun publishResults(constraint: CharSequence?, results: FilterResults?) { if (results != null && results.count > 0) { notifyDataSetChanged() } else { notifyDataSetInvalidated() } } } } }
Ebay-Android-APP/app/src/main/java/com/example/ebayhw4/AutoSuggestAdapter.kt
2417617513
package io.github.caimucheng.leaf.ide.viewmodel import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import io.github.caimucheng.leaf.common.mvi.MVIViewModel import io.github.caimucheng.leaf.common.mvi.UiIntent import io.github.caimucheng.leaf.common.mvi.UiState import io.github.caimucheng.leaf.ide.depository.MainDepository import kotlinx.coroutines.flow.collectLatest import kotlinx.coroutines.launch class MainViewModel : ViewModel() { private val mainDepository: MainDepository = MainDepository() fun initialize() { mainDepository.initialize() } }
LeafIDE/app/src/main/java/io/github/caimucheng/leaf/ide/viewmodel/MainViewModel.kt
203383392
package io.github.caimucheng.leaf.ide.viewmodel import android.text.SpannedString import androidx.lifecycle.viewModelScope import io.github.caimucheng.leaf.common.mvi.MVIViewModel import io.github.caimucheng.leaf.common.mvi.UiIntent import io.github.caimucheng.leaf.common.mvi.UiState import io.github.caimucheng.leaf.ide.R import io.github.caimucheng.leaf.ide.application.AppContext import io.github.caimucheng.leaf.ide.depository.SplashDepository import io.github.caimucheng.leaf.ide.util.language import kotlinx.coroutines.launch enum class SplashPage { PrivacyPolicy, UserAgreement, LaunchMode } enum class LaunchMode { LaunchFromExteralStorage, LaunchFromInternalStorage } data class SplashUiState( val titleResId: Int = R.string.privacy_policy, val content: SpannedString? = null, val page: SplashPage = SplashPage.PrivacyPolicy, val selectedLaunchMode: LaunchMode = LaunchMode.LaunchFromInternalStorage, val initializedLaunchMode: Boolean = false ) : UiState() sealed class SplashUiIntent : UiIntent() { data object NextPage : SplashUiIntent() data object PreviousPage : SplashUiIntent() data object InitializeLaunchMode : SplashUiIntent() data class GetContent(val page: SplashPage) : SplashUiIntent() data class SelectLaunchMode(val launchMode: LaunchMode) : SplashUiIntent() } class SplashViewModel : MVIViewModel<SplashUiState, SplashUiIntent>() { private val splashDepository = SplashDepository() override fun initialValue(): SplashUiState { return SplashUiState() } override fun handleIntent(intent: SplashUiIntent, currentState: SplashUiState) { when (intent) { is SplashUiIntent.GetContent -> { getContent(AppContext.current.language, intent.page) } SplashUiIntent.NextPage -> { nextPage() } SplashUiIntent.PreviousPage -> { previousPage() } is SplashUiIntent.SelectLaunchMode -> { selectLaunchMode(intent.launchMode) } SplashUiIntent.InitializeLaunchMode -> { initializeLaunchMode(state.value.selectedLaunchMode) } } } private fun initializeLaunchMode(launchMode: LaunchMode) { viewModelScope.launch { splashDepository.initializeLaunchMode(launchMode) setState(state.value.copy(initializedLaunchMode = true)) } } private fun selectLaunchMode(launchMode: LaunchMode) { viewModelScope.launch { setState(state.value.copy(selectedLaunchMode = launchMode)) } } private fun previousPage() { viewModelScope.launch { when (state.value.page) { SplashPage.PrivacyPolicy -> {} SplashPage.UserAgreement -> { val content = splashDepository.getContent( AppContext.current.language, SplashPage.PrivacyPolicy ) setState( state.value.copy( titleResId = R.string.privacy_policy, content = content, page = SplashPage.PrivacyPolicy ) ) } SplashPage.LaunchMode -> { val content = splashDepository.getContent( AppContext.current.language, SplashPage.UserAgreement ) setState( state.value.copy( titleResId = R.string.user_agreement, content = content, page = SplashPage.UserAgreement ) ) } } } } private fun nextPage() { viewModelScope.launch { when (state.value.page) { SplashPage.PrivacyPolicy -> { val content = splashDepository.getContent( AppContext.current.language, SplashPage.UserAgreement ) setState( state.value.copy( titleResId = R.string.user_agreement, content = content, page = SplashPage.UserAgreement ) ) } SplashPage.UserAgreement -> { val content = splashDepository.getContent( AppContext.current.language, SplashPage.LaunchMode ) setState( state.value.copy( titleResId = R.string.launch_mode, content = content, page = SplashPage.LaunchMode ) ) } SplashPage.LaunchMode -> {} } } } private fun getContent(language: String, page: SplashPage) { viewModelScope.launch { val content = splashDepository.getContent(language, page) setState(state.value.copy(content = content)) } } }
LeafIDE/app/src/main/java/io/github/caimucheng/leaf/ide/viewmodel/SplashViewModel.kt
682076574
package io.github.caimucheng.leaf.ide.viewmodel import android.content.Context import android.util.Log import androidx.fragment.app.FragmentManager import io.github.caimucheng.leaf.common.mvi.MVIAppViewModel import io.github.caimucheng.leaf.common.mvi.UiIntent import io.github.caimucheng.leaf.common.mvi.UiState import io.github.caimucheng.leaf.ide.depository.AppDepository import io.github.caimucheng.leaf.ide.model.Plugin import io.github.caimucheng.leaf.ide.model.Project import io.github.caimucheng.leaf.ide.model.isEnabled import io.github.caimucheng.leaf.ide.model.isSupported import io.github.caimucheng.leaf.ide.util.LeafIDEPluginRootPath import kotlinx.coroutines.CancellationException import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import java.io.File enum class PluginState { Loading, Done } enum class ProjectState { Loading, Done } data class AppState( val pluginState: PluginState = PluginState.Done, val plugins: List<Plugin> = emptyList(), val projectState: ProjectState = ProjectState.Done, val projects: List<Project> = emptyList(), val isRefreshed: Boolean = false ) : UiState() sealed class AppIntent : UiIntent() { data object Refresh : AppIntent() data class Install( val packageName: String, val context: Context, val fragmentManager: FragmentManager, val skipLifecycle: Boolean = false ) : AppIntent() data class Uninstall( val packageName: String, val context: Context, val fragmentManager: FragmentManager, val skipLifecycle: Boolean = false ) : AppIntent() data class Update( val packageName: String, val context: Context, val fragmentManager: FragmentManager, val skipLifecycle: Boolean = false ) : AppIntent() } object AppViewModel : MVIAppViewModel<AppState, AppIntent>() { private val appDepository: AppDepository = AppDepository() override fun initialValue(): AppState { return AppState() } override fun handleIntent(intent: AppIntent, currentState: AppState) { when (intent) { AppIntent.Refresh -> refresh() is AppIntent.Install -> install( intent.packageName, intent.context, intent.fragmentManager, intent.skipLifecycle ) is AppIntent.Uninstall -> uninstall( intent.packageName, intent.context, intent.fragmentManager, intent.skipLifecycle ) is AppIntent.Update -> update( intent.packageName, intent.context, intent.fragmentManager, intent.skipLifecycle ) } } private fun update( packageName: String, context: Context, fragmentManager: FragmentManager, skipLifecycle: Boolean ) { viewModelScope.launch { setState( state.value.copy( pluginState = PluginState.Loading, projectState = ProjectState.Loading ) ) val plugins = appDepository.refreshPlugins(state.value.plugins.filter { it.packageName != packageName }) val updatedPlugin = plugins.find { it.packageName == packageName } if (updatedPlugin != null) { if (!skipLifecycle) { try { withContext(Dispatchers.Main) { updatedPlugin.pluginAPP.onUpdate(context, fragmentManager) } } catch (e: Exception) { if (e is CancellationException) throw e e.printStackTrace() Log.e("AppViewModel", "Update plugin failed: " + e.message) } } } val projects = appDepository.refreshProjects(plugins.filter { it.isSupported && it.isEnabled }) setState( state.value.copy( pluginState = PluginState.Done, plugins = plugins, projectState = ProjectState.Done, projects = projects, isRefreshed = true ) ) } } private fun uninstall( packageName: String, context: Context, fragmentManager: FragmentManager, skipLifecycle: Boolean ) { viewModelScope.launch { setState( state.value.copy( pluginState = PluginState.Loading, projectState = ProjectState.Loading ) ) val plugins = ArrayList(appDepository.refreshPlugins(state.value.plugins)) val uninstalledPlugin = plugins.find { it.packageName == packageName } if (uninstalledPlugin != null) { val file = File(LeafIDEPluginRootPath, "${uninstalledPlugin.packageName}.apk") if (file.exists()) { file.delete() } plugins.remove(uninstalledPlugin) if (!skipLifecycle) { try { withContext(Dispatchers.Main) { uninstalledPlugin.pluginAPP.onUninstall(context, fragmentManager) } } catch (e: Exception) { if (e is CancellationException) throw e e.printStackTrace() Log.e("AppViewModel", "Uninstall plugin failed: " + e.message) } } } val projects = appDepository.refreshProjects(plugins.filter { it.isSupported && it.isEnabled }) setState( state.value.copy( pluginState = PluginState.Done, plugins = plugins, projectState = ProjectState.Done, projects = projects, isRefreshed = true ) ) } } private fun install( packageName: String, context: Context, fragmentManager: FragmentManager, skipLifecycle: Boolean ) { viewModelScope.launch { setState( state.value.copy( pluginState = PluginState.Loading, projectState = ProjectState.Loading ) ) val plugins = appDepository.refreshPlugins(state.value.plugins) val installedPlugin = plugins.find { it.packageName == packageName } if (installedPlugin != null) { if (!skipLifecycle) { try { withContext(Dispatchers.Main) { installedPlugin.pluginAPP.onInstall(context, fragmentManager) } } catch (e: Exception) { if (e is CancellationException) throw e e.printStackTrace() Log.e("AppViewModel", "Install plugin failed: " + e.message) } } } val projects = appDepository.refreshProjects(plugins.filter { it.isSupported && it.isEnabled }) setState( state.value.copy( pluginState = PluginState.Done, plugins = plugins, projectState = ProjectState.Done, projects = projects, isRefreshed = true ) ) } } private fun refresh() { viewModelScope.launch { setState( state.value.copy( pluginState = PluginState.Loading, projectState = ProjectState.Loading ) ) val plugins = appDepository.refreshPlugins(state.value.plugins) val projects = appDepository.refreshProjects(plugins.filter { it.isSupported && it.isEnabled }) setState( state.value.copy( pluginState = PluginState.Done, plugins = plugins, projectState = ProjectState.Done, projects = projects, isRefreshed = true ) ) } } }
LeafIDE/app/src/main/java/io/github/caimucheng/leaf/ide/viewmodel/AppViewModel.kt
2904199659
package io.github.caimucheng.leaf.ide.util import android.content.Context import android.content.SharedPreferences import androidx.core.content.ContextCompat import io.github.caimucheng.leaf.ide.application.AppContext import io.github.caimucheng.leaf.ide.viewmodel.LaunchMode const val LAUNCH_MODE_KEY = "launch_mode" const val PLUGIN_KEY = "plugin" inline val AppContext.launchModeSharedPreferences: SharedPreferences get() { return getSharedPreferences(LAUNCH_MODE_KEY, Context.MODE_PRIVATE) } inline val AppContext.pluginSharedPreferences: SharedPreferences get() { return getSharedPreferences(PLUGIN_KEY, Context.MODE_PRIVATE) } inline val AppContext.isInitializedLaunchMode: Boolean get() { return launchModeSharedPreferences.getString("launchMode", null) != null } inline val AppContext.launchMode: LaunchMode get() { val launchMode = launchModeSharedPreferences.getString("launchMode", null) ?: return LaunchMode.LaunchFromInternalStorage return LaunchMode.valueOf(launchMode) } inline val AppContext.language: String get() { return ContextCompat.getString(this, io.github.caimucheng.leaf.common.R.string.language) }
LeafIDE/app/src/main/java/io/github/caimucheng/leaf/ide/util/Common.kt
2957163484
package io.github.caimucheng.leaf.ide.util import android.os.Environment import io.github.caimucheng.leaf.ide.application.AppContext import io.github.caimucheng.leaf.ide.viewmodel.LaunchMode import java.io.File val ExternalRootPath: File = Environment.getExternalStorageDirectory() inline val LeafIDEPluginRootPath: File get() { return File(AppContext.current.filesDir, "plugins") } inline val LeafIDERootPath: File get() { return when (AppContext.current.launchMode) { LaunchMode.LaunchFromExteralStorage -> File(ExternalRootPath, "LeafIDE") LaunchMode.LaunchFromInternalStorage -> File(AppContext.current.filesDir, "LeafIDE") } } val LeafIDEProjectPath: File by lazy { File(LeafIDERootPath, "projects") }
LeafIDE/app/src/main/java/io/github/caimucheng/leaf/ide/util/Path.kt
4149502312
package io.github.caimucheng.leaf.ide.activity import android.os.Bundle import android.util.Log import androidx.fragment.app.FragmentManager import io.github.caimucheng.leaf.ide.databinding.ActivityMainBinding import java.lang.ref.WeakReference class MainActivity : BaseActivity() { private lateinit var viewBinding: ActivityMainBinding companion object { var currentMainActivity: WeakReference<MainActivity>? = null private set } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) currentMainActivity = WeakReference(this) viewBinding = ActivityMainBinding.inflate(layoutInflater) setContentView(viewBinding.root) } }
LeafIDE/app/src/main/java/io/github/caimucheng/leaf/ide/activity/MainActivity.kt
3302284962
package io.github.caimucheng.leaf.ide.activity import android.os.Bundle import android.view.View import androidx.appcompat.app.AppCompatActivity import androidx.core.content.ContextCompat import androidx.core.view.WindowCompat import io.github.caimucheng.leaf.common.R abstract class BaseActivity : AppCompatActivity() { @Suppress("DEPRECATION") override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) WindowCompat.setDecorFitsSystemWindows(window, true) val isDark = ContextCompat.getString(this, R.string.is_ui_dark).toBooleanStrictOrNull() ?: false val windowInsetsController = WindowCompat.getInsetsController(window, window.decorView.apply { systemUiVisibility = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION }) windowInsetsController.isAppearanceLightStatusBars = !isDark windowInsetsController.isAppearanceLightNavigationBars = !isDark } }
LeafIDE/app/src/main/java/io/github/caimucheng/leaf/ide/activity/BaseActivity.kt
602477339
package io.github.caimucheng.leaf.ide.activity import android.content.ClipData import android.content.ClipboardManager import android.content.Context import android.content.Intent import android.os.Bundle import io.github.caimucheng.leaf.ide.R import io.github.caimucheng.leaf.ide.databinding.ActivityCrashHandlerBinding class CrashHandlerActivity : BaseActivity() { private lateinit var viewBinding: ActivityCrashHandlerBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) viewBinding = ActivityCrashHandlerBinding.inflate(layoutInflater) setContentView(viewBinding.root) val deviceInfo = intent.getStringExtra("deviceInfo") ?: "null" val threadGroup = intent.getStringExtra("threadGroup") ?: "null" val thread = intent.getStringExtra("thread") ?: "null" val exception = intent.getStringExtra("exception") ?: "null" val all = buildString { appendLine(getString(R.string.app_crashed_header)) appendLine() appendLine(getString(R.string.device_info)) appendLine(deviceInfo) appendLine() appendLine(getString(R.string.thread_group, threadGroup)) appendLine(getString(R.string.thread, thread)) appendLine(getString(R.string.exception, exception)) } viewBinding.description.text = all viewBinding.copyButton.setOnClickListener { val clipboardManager = getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager clipboardManager.setPrimaryClip(ClipData.newPlainText("exception", all)) } viewBinding.restartButton.setOnClickListener { val intent = packageManager.getLaunchIntentForPackage(packageName) ?: return@setOnClickListener intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP) startActivity(intent) android.os.Process.killProcess(android.os.Process.myPid()) } } }
LeafIDE/app/src/main/java/io/github/caimucheng/leaf/ide/activity/CrashHandlerActivity.kt
3391564945
package io.github.caimucheng.leaf.ide.adapter import android.content.Context import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import io.github.caimucheng.leaf.ide.R import io.github.caimucheng.leaf.ide.databinding.LayoutMainHomeBinding import io.github.caimucheng.leaf.ide.model.Project class MainHomeAdapter( private val context: Context, private val projects: List<Project> ) : RecyclerView.Adapter<MainHomeAdapter.ViewHolder>() { private val inflater by lazy { LayoutInflater.from(context) } inner class ViewHolder(val viewBinding: LayoutMainHomeBinding) : RecyclerView.ViewHolder(viewBinding.root) override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { return ViewHolder(LayoutMainHomeBinding.inflate(inflater, parent, false)) } override fun getItemCount(): Int { return projects.size } override fun onBindViewHolder(holder: ViewHolder, position: Int) { val project = projects[position] val viewBinding = holder.viewBinding viewBinding.projectName.text = project.name viewBinding.projectDescription.text = context.getString(R.string.project_description, project.description) viewBinding.pluginSupport.text = context.getString(R.string.plugin_support, project.plugin.packageName) viewBinding.icon.background = project.plugin.pluginAPP.getProjectCardIcon() viewBinding.subscript.text = project.plugin.pluginAPP.getProjectCardSubscript() } }
LeafIDE/app/src/main/java/io/github/caimucheng/leaf/ide/adapter/MainHomeAdapter.kt
2509969037
package io.github.caimucheng.leaf.ide.adapter import android.content.Context import android.content.Intent import android.net.Uri import android.view.LayoutInflater import android.view.MenuInflater import android.view.View import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import io.github.caimucheng.leaf.ide.R import io.github.caimucheng.leaf.ide.databinding.LayoutMainPluginBinding import io.github.caimucheng.leaf.ide.model.Plugin import io.github.caimucheng.leaf.ide.model.description import io.github.caimucheng.leaf.ide.model.isEnabled import io.github.caimucheng.leaf.ide.model.isSupported import io.github.caimucheng.leaf.ide.model.name import io.github.caimucheng.leaf.ide.model.toggle import io.github.caimucheng.leaf.ide.viewmodel.AppIntent import io.github.caimucheng.leaf.ide.viewmodel.AppViewModel class MainPluginAdapter( private val context: Context, private val plugins: List<Plugin>, private val onToggle: (plugin: Plugin) -> Unit, private val onUninstall: (plugin: Plugin) -> Unit ) : RecyclerView.Adapter<MainPluginAdapter.ViewHolder>() { private val inflater by lazy { LayoutInflater.from(context) } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { return ViewHolder(LayoutMainPluginBinding.inflate(inflater, parent, false)) } override fun getItemCount(): Int { return plugins.size } override fun onBindViewHolder(holder: ViewHolder, position: Int) { val plugin = plugins[position] val viewBinding = holder.viewBinding viewBinding.icon.background = plugin.icon viewBinding.title.text = plugin.name viewBinding.description.text = plugin.description viewBinding.description.post { val ellipsisCount = viewBinding.description.layout.getEllipsisCount(viewBinding.description.lineCount - 1) if (ellipsisCount > 0) { var isExpanded = false viewBinding.expand.visibility = View.VISIBLE viewBinding.expand.setOnClickListener { isExpanded = !isExpanded if (isExpanded) { viewBinding.expand.text = context.getString(R.string.collapse) viewBinding.description.maxLines = Int.MAX_VALUE } else { viewBinding.expand.text = context.getString(R.string.expand) viewBinding.description.maxLines = 2 } } } } viewBinding.root.setOnCreateContextMenuListener { menu, _, _ -> val menuInflater = MenuInflater(context) menu.setHeaderTitle(plugin.name) menuInflater.inflate(R.menu.menu_main_plugin_popup, menu) val titleResId = if (plugin.isEnabled) R.string.disable else R.string.enable val enableItem = menu.findItem(R.id.enable) enableItem.title = context.getString(titleResId) enableItem.setOnMenuItemClickListener { plugin.toggle() enableItem.title = context.getString(if (plugin.isEnabled) R.string.disable else R.string.enable) onToggle(plugin) false } val uninstallItem = menu.findItem(R.id.uninstall) uninstallItem.setOnMenuItemClickListener { onUninstall(plugin) false } } if (plugin.isEnabled && plugin.isSupported) { viewBinding.constraintLayout.alpha = 1f } else { viewBinding.constraintLayout.alpha = 0.6f } if (!plugin.isSupported) { viewBinding.unsupported.visibility = View.VISIBLE } } inner class ViewHolder(val viewBinding: LayoutMainPluginBinding) : RecyclerView.ViewHolder(viewBinding.root) }
LeafIDE/app/src/main/java/io/github/caimucheng/leaf/ide/adapter/MainPluginAdapter.kt
3814549136
package io.github.caimucheng.leaf.ide.adapter import android.content.Context import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import io.github.caimucheng.leaf.ide.databinding.LayoutTemplateBinding import io.github.caimucheng.leaf.ide.model.Plugin class TemplateAdapter( private val context: Context, private val plugins: List<Plugin>, private val onItemClick: (plugin: Plugin) -> Unit ) : RecyclerView.Adapter<TemplateAdapter.ViewHolder>() { inner class ViewHolder(val viewBinding: LayoutTemplateBinding) : RecyclerView.ViewHolder(viewBinding.root) private val inflater by lazy { LayoutInflater.from(context) } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { return ViewHolder(LayoutTemplateBinding.inflate(inflater, parent, false)) } override fun getItemCount(): Int { return plugins.size } override fun onBindViewHolder(holder: ViewHolder, position: Int) { val viewBinding = holder.viewBinding val plugin = plugins[position] viewBinding.icon.background = plugin.pluginAPP.getTemplateIcon() viewBinding.title.text = plugin.pluginAPP.getTemplateTitle() viewBinding.root.setOnClickListener { onItemClick(plugin) } } }
LeafIDE/app/src/main/java/io/github/caimucheng/leaf/ide/adapter/TemplateAdapter.kt
1053872515
package io.github.caimucheng.leaf.ide.depository import android.graphics.Typeface import android.text.Spannable import android.text.SpannedString import android.text.style.RelativeSizeSpan import android.text.style.StyleSpan import androidx.core.content.edit import androidx.core.text.buildSpannedString import io.github.caimucheng.leaf.ide.application.AppContext import io.github.caimucheng.leaf.ide.util.launchModeSharedPreferences import io.github.caimucheng.leaf.ide.viewmodel.LaunchMode import io.github.caimucheng.leaf.ide.viewmodel.SplashPage import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext class SplashDepository { private data class Token( val text: String, val type: String ) suspend fun getContent(language: String, page: SplashPage): SpannedString? { return withContext(Dispatchers.IO) { val assets = AppContext.current.assets val target = when (page) { SplashPage.PrivacyPolicy -> "PrivacyPolicy" SplashPage.UserAgreement -> "UserAgreement" SplashPage.LaunchMode -> "LaunchMode" } runCatching { assets.open("protocol/$language/$target.txt").bufferedReader().use { parseProtocol(it.readText()) } }.getOrNull() } } private fun parseProtocol(text: String): SpannedString { val tokens: MutableList<Token> = ArrayList() var index = 0 var ch: Char val cache = StringBuilder() var inTitleContext = false var inBoldContext = false while (index < text.length) { ch = text[index] when { ch == '<' && !inTitleContext -> { inTitleContext = true if (cache.isNotEmpty()) { tokens.add(Token(cache.toString(), "text")) cache.clear() } } ch == '>' && inTitleContext -> { inTitleContext = false if (cache.isNotEmpty()) { tokens.add(Token(cache.toString(), "title")) cache.clear() } } ch == '(' && !inBoldContext -> { inBoldContext = true if (cache.isNotEmpty()) { tokens.add(Token(cache.toString(), "text")) cache.clear() } } ch == ')' && inBoldContext -> { inBoldContext = false if (cache.isNotEmpty()) { tokens.add(Token(cache.toString(), "bold")) cache.clear() } } ch == '{' -> { cache.append("(") } ch == '}' -> { cache.append(")") } else -> { cache.append(ch) } } index++ } if (index == text.length) { if (inTitleContext) { tokens.add(Token(cache.toString(), "title")) cache.clear() } else { tokens.add(Token(cache.toString(), "text")) cache.clear() } if (inBoldContext) { tokens.add(Token(cache.toString(), "bold")) cache.clear() } else { tokens.add(Token(cache.toString(), "text")) cache.clear() } } return buildSpannedString { for (token in tokens) { when (token.type) { "title" -> { val start = length if (isNotEmpty()) { appendLine() } append( token.text ) setSpan( StyleSpan(Typeface.BOLD), start, length, Spannable.SPAN_INCLUSIVE_EXCLUSIVE ) setSpan( RelativeSizeSpan(1.3f), start, length, Spannable.SPAN_INCLUSIVE_EXCLUSIVE ) appendLine() } "bold" -> { val start = length append( token.text, ) setSpan( StyleSpan(Typeface.BOLD), start, length, Spannable.SPAN_INCLUSIVE_EXCLUSIVE ) } else -> { append( token.text, ) } } } } } suspend fun initializeLaunchMode(launchMode: LaunchMode) { return withContext(Dispatchers.IO) { val sharedPreferences = AppContext.current.launchModeSharedPreferences sharedPreferences.edit { putString("launchMode", launchMode.name) } } } }
LeafIDE/app/src/main/java/io/github/caimucheng/leaf/ide/depository/SplashDepository.kt
4206123254
package io.github.caimucheng.leaf.ide.depository import io.github.caimucheng.leaf.ide.util.LeafIDEPluginRootPath import io.github.caimucheng.leaf.ide.util.LeafIDEProjectPath import io.github.caimucheng.leaf.ide.util.LeafIDERootPath import java.io.File class MainDepository { fun initialize() { createPluginRoot() createLeafIDERoot() createLeafIDEProject() } private fun createPluginRoot() { LeafIDEPluginRootPath.mkdirs() } private fun createLeafIDERoot() { LeafIDEProjectPath.mkdirs() } private fun createLeafIDEProject() { LeafIDEProjectPath.mkdirs() runCatching { File(LeafIDERootPath, ".nomedia") .createNewFile() } } }
LeafIDE/app/src/main/java/io/github/caimucheng/leaf/ide/depository/MainDepository.kt
24832273
package io.github.caimucheng.leaf.ide.depository import android.content.pm.PackageManager import android.os.Build import dalvik.system.DexClassLoader import io.github.caimucheng.leaf.ide.application.AppContext import io.github.caimucheng.leaf.ide.model.Plugin import io.github.caimucheng.leaf.ide.model.Project import io.github.caimucheng.leaf.ide.util.ExternalRootPath import io.github.caimucheng.leaf.ide.util.LeafIDEPluginRootPath import io.github.caimucheng.leaf.ide.util.LeafIDEProjectPath import io.github.caimucheng.leaf.ide.util.LeafIDERootPath import io.github.caimucheng.leaf.plugin.PluginAPP import io.github.caimucheng.leaf.plugin.path.Paths import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.supervisorScope import kotlinx.coroutines.withContext import org.json.JSONObject import java.io.File class AppDepository { companion object { const val PLUGIN_MIN_VERSION = 1 } suspend fun refreshProjects(plugins: List<Plugin>): List<Project> { return withContext(Dispatchers.IO) { val projects: MutableList<Project> = ArrayList() supervisorScope { val children = LeafIDEProjectPath.listFiles() ?: emptyArray() for (child in children) { runCatching { if (child.isFile) return@runCatching val configurationDir = File(child, ".LeafIDE") if (configurationDir.isFile || !configurationDir.exists()) return@runCatching val workspaceFile = File(configurationDir, "workspace.json") if (!workspaceFile.exists() || workspaceFile.isDirectory) return@runCatching val workspace = JSONObject(workspaceFile.bufferedReader().use { it.readText() }) val projectName = workspace.optString("name") val projectDescription = workspace.optString("description") val pluginSupport = workspace.optString("pluginSupport") val plugin = plugins.find { it.packageName == pluginSupport } ?: return@runCatching projects.add(Project(projectName, projectDescription, plugin, workspace)) } } } projects.toList() } } suspend fun refreshPlugins(loadedPlugins: List<Plugin>): List<Plugin> { return withContext(Dispatchers.IO) { val plugins: MutableList<Plugin> = ArrayList() val context = AppContext.current val children = LeafIDEPluginRootPath.listFiles() ?: emptyArray() for (child in children) { if (child.isDirectory || !child.name.endsWith(".apk")) { continue } val loadedPlugin = loadedPlugins.find { plugin -> plugin.packageName == child.name } if (loadedPlugin != null) { plugins.add(loadedPlugin) continue } runCatching { val packageInfo = context.packageManager.getPackageArchiveInfo( child.absolutePath, PackageManager.GET_META_DATA ) ?: return@runCatching val application = packageInfo.applicationInfo application.sourceDir = child.absolutePath application.publicSourceDir = child.absolutePath val icon = application.loadIcon(context.packageManager) val packageName = application.packageName val versionName = packageInfo.versionName val versionCode = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { packageInfo.longVersionCode } else { @Suppress("DEPRECATION") packageInfo.versionCode.toLong() } val metaData = application.metaData ?: return@runCatching if (!metaData.getBoolean("leafide_plugin", false)) { return@runCatching } val entrance = application.name ?: return@runCatching val pluginMinVersion = metaData.getInt("plugin_min_version", PLUGIN_MIN_VERSION) val resources = context.packageManager.getResourcesForApplication(application) val classLoader = DexClassLoader( child.absolutePath, context.cacheDir.absolutePath, null, context.classLoader ) val pluginAPPClass = classLoader.loadClass(entrance) val isChild = PluginAPP::class.java.isAssignableFrom(pluginAPPClass) if (!isChild) { return@runCatching } // Get pluginAPP val paths = Paths( ExternalRootPath, LeafIDEPluginRootPath, LeafIDERootPath, LeafIDEProjectPath ) val pluginAPP = pluginAPPClass.getConstructor().newInstance() as PluginAPP pluginAPP.onCreate(context, resources, paths) plugins.add( Plugin( icon = icon, packageName = packageName, versionName = versionName, versionCode = versionCode, entrance = entrance, pluginMinVersion = pluginMinVersion, pluginAPP = pluginAPP ) ) }.exceptionOrNull()?.printStackTrace() } plugins.toList() } } }
LeafIDE/app/src/main/java/io/github/caimucheng/leaf/ide/depository/AppDepository.kt
2313100031
package io.github.caimucheng.leaf.ide.fragment import android.Manifest import android.content.pm.PackageManager import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.activity.result.contract.ActivityResultContracts import androidx.core.content.ContextCompat import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import androidx.lifecycle.Lifecycle import androidx.lifecycle.lifecycleScope import androidx.lifecycle.repeatOnLifecycle import androidx.navigation.Navigation import es.dmoral.toasty.Toasty import io.github.caimucheng.leaf.ide.R import io.github.caimucheng.leaf.ide.application.AppContext import io.github.caimucheng.leaf.ide.databinding.FragmentSplashBinding import io.github.caimucheng.leaf.ide.util.isInitializedLaunchMode import io.github.caimucheng.leaf.ide.util.launchMode import io.github.caimucheng.leaf.ide.util.launchModeSharedPreferences import io.github.caimucheng.leaf.ide.viewmodel.LaunchMode import io.github.caimucheng.leaf.ide.viewmodel.SplashPage import io.github.caimucheng.leaf.ide.viewmodel.SplashUiIntent import io.github.caimucheng.leaf.ide.viewmodel.SplashViewModel import kotlinx.coroutines.cancel import kotlinx.coroutines.flow.collectLatest import kotlinx.coroutines.launch class SplashFragment : Fragment() { private lateinit var viewBinding: FragmentSplashBinding private val splashViewModel: SplashViewModel by viewModels() override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { viewBinding = FragmentSplashBinding.inflate(inflater, container, false) return viewBinding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val navController = Navigation.findNavController(view) val activityResultLauncher = registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { results -> val writable = results[Manifest.permission.WRITE_EXTERNAL_STORAGE] ?: false val readable = results[Manifest.permission.READ_EXTERNAL_STORAGE] ?: false when { writable && readable -> { viewLifecycleOwner.lifecycleScope.launch { splashViewModel.intent.send(SplashUiIntent.InitializeLaunchMode) } } writable -> { Toasty.error(requireContext(), R.string.no_readable, Toasty.LENGTH_SHORT) .show() } readable -> { Toasty.error(requireContext(), R.string.no_writable, Toasty.LENGTH_SHORT) .show() } else -> { Toasty.error( requireContext(), R.string.no_writable_and_readable, Toasty.LENGTH_SHORT ).show() } } } if (AppContext.current.isInitializedLaunchMode) { when (AppContext.current.launchMode) { LaunchMode.LaunchFromExteralStorage -> { val writable = ContextCompat.checkSelfPermission( requireContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE ) == PackageManager.PERMISSION_GRANTED val readable = ContextCompat.checkSelfPermission( requireContext(), Manifest.permission.READ_EXTERNAL_STORAGE ) == PackageManager.PERMISSION_GRANTED if (writable && readable) { navController.navigate(R.id.action_splashFragment_to_mainFragment) return } } LaunchMode.LaunchFromInternalStorage -> { navController.navigate(R.id.action_splashFragment_to_mainFragment) return } } } viewLifecycleOwner.lifecycleScope.launch { repeatOnLifecycle(Lifecycle.State.STARTED) { splashViewModel.intent.send(SplashUiIntent.GetContent(splashViewModel.state.value.page)) splashViewModel.state.collectLatest { val newTitle = getString(it.titleResId) if (viewBinding.toolbar.title != newTitle) { viewBinding.toolbar.visibility = View.INVISIBLE viewBinding.toolbar.title = newTitle viewBinding.toolbar.visibility = View.VISIBLE } when (it.page) { SplashPage.PrivacyPolicy -> { viewBinding.privacyPolicyContent.text = it.content viewBinding.userAgreementPage.visibility = View.GONE viewBinding.launchModePage.visibility = View.GONE viewBinding.privacyPolicyPage.visibility = View.VISIBLE viewBinding.previousIcon.visibility = View.GONE viewBinding.closeIcon.visibility = View.VISIBLE } SplashPage.UserAgreement -> { viewBinding.userAgreementContent.text = it.content viewBinding.privacyPolicyPage.visibility = View.GONE viewBinding.launchModePage.visibility = View.GONE viewBinding.userAgreementPage.visibility = View.VISIBLE viewBinding.closeIcon.visibility = View.GONE viewBinding.doneIcon.visibility = View.GONE viewBinding.previousIcon.visibility = View.VISIBLE viewBinding.nextIcon.visibility = View.VISIBLE } SplashPage.LaunchMode -> { viewBinding.launchModeContent.text = it.content viewBinding.privacyPolicyPage.visibility = View.GONE viewBinding.userAgreementPage.visibility = View.GONE viewBinding.launchModePage.visibility = View.VISIBLE viewBinding.closeIcon.visibility = View.GONE viewBinding.nextIcon.visibility = View.GONE viewBinding.previousIcon.visibility = View.VISIBLE viewBinding.doneIcon.visibility = View.VISIBLE } } when (it.selectedLaunchMode) { LaunchMode.LaunchFromExteralStorage -> { viewBinding.launchFromExternalStorageRadioButton.isChecked = true viewBinding.launchFromInternalStorageRadioButton.isChecked = false } LaunchMode.LaunchFromInternalStorage -> { viewBinding.launchFromInternalStorageRadioButton.isChecked = true viewBinding.launchFromExternalStorageRadioButton.isChecked = false } } if (it.initializedLaunchMode) { navController.navigate(R.id.action_splashFragment_to_mainFragment) } } } } viewBinding.previousButton.setOnClickListener { if (splashViewModel.state.value.page == SplashPage.PrivacyPolicy) { requireActivity().finish() return@setOnClickListener } viewLifecycleOwner.lifecycleScope.launch { splashViewModel.intent.send(SplashUiIntent.PreviousPage) } } viewBinding.nextButton.setOnClickListener { if (splashViewModel.state.value.page == SplashPage.LaunchMode) { when (splashViewModel.state.value.selectedLaunchMode) { LaunchMode.LaunchFromExteralStorage -> activityResultLauncher.launch( arrayOf( Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE ) ) LaunchMode.LaunchFromInternalStorage -> activityResultLauncher.launch( arrayOf( Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE ) ) } return@setOnClickListener } viewLifecycleOwner.lifecycleScope.launch { splashViewModel.intent.send(SplashUiIntent.NextPage) } } // viewBinding.launchFromExternalStorageCard.setOnClickListener { // viewLifecycleOwner.lifecycleScope.launch { // splashViewModel.intent.send(SplashUiIntent.SelectLaunchMode(LaunchMode.LaunchFromExteralStorage)) // } // } viewBinding.launchFromInternalStorageCard.setOnClickListener { viewLifecycleOwner.lifecycleScope.launch { splashViewModel.intent.send(SplashUiIntent.SelectLaunchMode(LaunchMode.LaunchFromInternalStorage)) } } } }
LeafIDE/app/src/main/java/io/github/caimucheng/leaf/ide/fragment/SplashFragment.kt
3504829511
package io.github.caimucheng.leaf.ide.fragment import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.lifecycle.lifecycleScope import androidx.navigation.fragment.findNavController import io.github.caimucheng.leaf.ide.R import io.github.caimucheng.leaf.ide.databinding.FragmentNewProjectBinding import io.github.caimucheng.leaf.ide.viewmodel.AppIntent import io.github.caimucheng.leaf.ide.viewmodel.AppViewModel import io.github.caimucheng.leaf.ide.viewmodel.PluginState import io.github.caimucheng.leaf.plugin.action.ActionHolder import io.github.caimucheng.leaf.plugin.fragment.PluginFragment import kotlinx.coroutines.flow.collectLatest import kotlinx.coroutines.launch class NewProjectFragment : Fragment() { private lateinit var viewBinding: FragmentNewProjectBinding override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { viewBinding = FragmentNewProjectBinding.inflate(inflater, container, false) return viewBinding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) setupIconButton() val packageName = arguments?.getString("packageName") ?: return run { findNavController().popBackStack() } viewLifecycleOwner.lifecycleScope.launch { AppViewModel.state.collectLatest { when (it.pluginState) { PluginState.Loading -> { viewBinding.content.visibility = View.GONE viewBinding.placeholder.visibility = View.GONE viewBinding.loading.visibility = View.VISIBLE } PluginState.Done -> { viewBinding.loading.visibility = View.GONE val plugin = it.plugins.find { plugin -> plugin.packageName == packageName } if (plugin != null) { viewBinding.placeholder.visibility = View.GONE viewBinding.content.visibility = View.VISIBLE val fragmentCreator = plugin.pluginAPP.getFragmentCreator() val onNewProjectFragment = fragmentCreator.onNewProject() setupFragment(onNewProjectFragment) childFragmentManager.beginTransaction() .setCustomAnimations( androidx.navigation.ui.R.anim.nav_default_enter_anim, androidx.navigation.ui.R.anim.nav_default_exit_anim, androidx.navigation.ui.R.anim.nav_default_pop_enter_anim, androidx.navigation.ui.R.anim.nav_default_pop_exit_anim ) .replace(R.id.content, onNewProjectFragment) .commit() } else { viewBinding.content.visibility = View.GONE viewBinding.placeholder.visibility = View.VISIBLE } } } } } } private fun setupFragment(onNewProjectFragment: PluginFragment) { val actionHolder = ActionHolder( onPopBackStack = { findNavController().popBackStack() }, onPopBackHome = { if (it) { viewLifecycleOwner.lifecycleScope.launch { AppViewModel.intent.send(AppIntent.Refresh) findNavController().navigate(R.id.action_newProjectFragment_to_mainFragment) } } else { findNavController().navigate(R.id.action_newProjectFragment_to_mainFragment) } }, onStartFragment = { setupFragment(it) childFragmentManager.beginTransaction() .setCustomAnimations( androidx.navigation.ui.R.anim.nav_default_enter_anim, androidx.navigation.ui.R.anim.nav_default_exit_anim, androidx.navigation.ui.R.anim.nav_default_pop_enter_anim, androidx.navigation.ui.R.anim.nav_default_pop_exit_anim ) .replace(R.id.content, it) .addToBackStack(null) .commit() }, onReplaceFragment = { setupFragment(it) childFragmentManager.beginTransaction() .setCustomAnimations( androidx.navigation.ui.R.anim.nav_default_enter_anim, androidx.navigation.ui.R.anim.nav_default_exit_anim, androidx.navigation.ui.R.anim.nav_default_pop_enter_anim, androidx.navigation.ui.R.anim.nav_default_pop_exit_anim ) .replace(R.id.content, it) .commit() } ) onNewProjectFragment.onPrepareActionHolder(actionHolder) } private fun setupIconButton() { viewBinding.iconButton.setOnClickListener { findNavController().popBackStack() } } }
LeafIDE/app/src/main/java/io/github/caimucheng/leaf/ide/fragment/NewProjectFragment.kt
207971937
package io.github.caimucheng.leaf.ide.fragment import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.core.os.bundleOf import androidx.fragment.app.Fragment import androidx.lifecycle.Lifecycle import androidx.lifecycle.lifecycleScope import androidx.lifecycle.repeatOnLifecycle import androidx.navigation.fragment.findNavController import androidx.recyclerview.widget.GridLayoutManager import androidx.recyclerview.widget.LinearLayoutManager import io.github.caimucheng.leaf.ide.R import io.github.caimucheng.leaf.ide.adapter.MainPluginAdapter import io.github.caimucheng.leaf.ide.adapter.TemplateAdapter import io.github.caimucheng.leaf.ide.databinding.FragmentTemplateProjectBinding import io.github.caimucheng.leaf.ide.model.Plugin import io.github.caimucheng.leaf.ide.model.isEnabled import io.github.caimucheng.leaf.ide.model.isSupported import io.github.caimucheng.leaf.ide.viewmodel.AppViewModel import io.github.caimucheng.leaf.ide.viewmodel.PluginState import kotlinx.coroutines.flow.collectLatest import kotlinx.coroutines.flow.map import kotlinx.coroutines.launch class TemplateProjectFragment : Fragment() { private lateinit var viewBinding: FragmentTemplateProjectBinding private val plugins by lazy { ArrayList<Plugin>(AppViewModel.state.value.plugins.filter { it.isSupported && it.isEnabled }) } private val adapter by lazy { TemplateAdapter( context = requireContext(), plugins = plugins, onItemClick = { plugin -> findNavController() .navigate( R.id.action_templateProjectFragment_to_newProjectFragment, bundleOf( "packageName" to plugin.packageName ) ) } ) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { viewBinding = FragmentTemplateProjectBinding.inflate(inflater, container, false) return viewBinding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) setupToolbar() setupRecyclerView() viewLifecycleOwner.lifecycleScope.launch { repeatOnLifecycle(Lifecycle.State.STARTED) { AppViewModel.state.map { it.copy( plugins = it.plugins.filter { plugin -> plugin.isSupported && plugin.isEnabled } ) }.collectLatest { when (it.pluginState) { PluginState.Loading -> { viewBinding.content.visibility = View.GONE viewBinding.placeholder.visibility = View.GONE viewBinding.loading.visibility = View.VISIBLE } PluginState.Done -> { viewBinding.loading.visibility = View.GONE plugins.clear() plugins.addAll(it.plugins) if (plugins.isNotEmpty()) { viewBinding.placeholder.visibility = View.GONE viewBinding.content.visibility = View.VISIBLE } else { viewBinding.content.visibility = View.GONE viewBinding.placeholder.visibility = View.VISIBLE } } } } } } } private fun setupToolbar() { viewBinding.materialToolbar.setNavigationOnClickListener { findNavController().popBackStack() } } private fun setupRecyclerView() { viewBinding.recyclerView.layoutManager = GridLayoutManager(requireContext(), 2, GridLayoutManager.VERTICAL, false) viewBinding.recyclerView.adapter = adapter } }
LeafIDE/app/src/main/java/io/github/caimucheng/leaf/ide/fragment/TemplateProjectFragment.kt
2898256359
package io.github.caimucheng.leaf.ide.fragment.main import android.annotation.SuppressLint import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.lifecycle.Lifecycle import androidx.lifecycle.lifecycleScope import androidx.lifecycle.repeatOnLifecycle import androidx.navigation.fragment.findNavController import androidx.recyclerview.widget.LinearLayoutManager import io.github.caimucheng.leaf.common.fragment.ProgressFragment import io.github.caimucheng.leaf.ide.R import io.github.caimucheng.leaf.ide.adapter.MainHomeAdapter import io.github.caimucheng.leaf.ide.databinding.FragmentMainHomeBinding import io.github.caimucheng.leaf.ide.fragment.MainFragment import io.github.caimucheng.leaf.ide.model.Project import io.github.caimucheng.leaf.ide.viewmodel.AppViewModel import io.github.caimucheng.leaf.ide.viewmodel.ProjectState import kotlinx.coroutines.flow.collectLatest import kotlinx.coroutines.launch class MainHomeFragment : Fragment() { private lateinit var viewBinding: FragmentMainHomeBinding private val projects by lazy { ArrayList<Project>(AppViewModel.state.value.projects) } private val adapter by lazy { MainHomeAdapter(requireContext(), projects) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { viewBinding = FragmentMainHomeBinding.inflate(inflater, container, false) return viewBinding.root } @SuppressLint("NotifyDataSetChanged") override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) setupRecyclerView() setupFab() viewLifecycleOwner.lifecycleScope.launch { repeatOnLifecycle(Lifecycle.State.STARTED) { AppViewModel.state.collectLatest { when (it.projectState) { ProjectState.Loading -> { viewBinding.content.visibility = View.GONE viewBinding.placeholder.visibility = View.GONE viewBinding.loading.visibility = View.VISIBLE } ProjectState.Done -> { viewBinding.loading.visibility = View.GONE projects.clear() projects.addAll(it.projects) adapter.notifyDataSetChanged() if (projects.isNotEmpty()) { viewBinding.placeholder.visibility = View.GONE viewBinding.content.visibility = View.VISIBLE } else { viewBinding.content.visibility = View.GONE viewBinding.placeholder.visibility = View.VISIBLE } } } } } } } private fun setupFab() { val rootFragment = requireActivity().supportFragmentManager.findFragmentById(R.id.fragmentContainerView) val mainFragment = rootFragment?.childFragmentManager?.fragments?.get(0) as? MainFragment viewBinding.fab1.setOnClickListener { mainFragment?.findNavController() ?.navigate(R.id.action_mainFragment_to_templateProjectFragment) } viewBinding.fab2.setOnClickListener { mainFragment?.findNavController() ?.navigate(R.id.action_mainFragment_to_templateProjectFragment) } } private fun setupRecyclerView() { viewBinding.recyclerView.layoutManager = LinearLayoutManager(requireContext(), LinearLayoutManager.VERTICAL, false) viewBinding.recyclerView.adapter = adapter } }
LeafIDE/app/src/main/java/io/github/caimucheng/leaf/ide/fragment/main/MainHomeFragment.kt
3659065030
package io.github.caimucheng.leaf.ide.fragment.main import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import io.github.caimucheng.leaf.ide.databinding.FragmentMainLeafFlowBinding class MainLeafFlowFragment : Fragment() { private lateinit var viewBinding: FragmentMainLeafFlowBinding override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { viewBinding = FragmentMainLeafFlowBinding.inflate(inflater, container, false) return viewBinding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) } }
LeafIDE/app/src/main/java/io/github/caimucheng/leaf/ide/fragment/main/MainLeafFlowFragment.kt
3097187201
package io.github.caimucheng.leaf.ide.fragment.main import android.annotation.SuppressLint import android.content.pm.PackageManager import android.os.Bundle import android.view.LayoutInflater import android.view.Menu import android.view.MenuInflater import android.view.MenuItem import android.view.View import android.view.ViewGroup import androidx.core.os.bundleOf import androidx.core.view.MenuProvider import androidx.fragment.app.Fragment import androidx.lifecycle.Lifecycle import androidx.lifecycle.lifecycleScope import androidx.lifecycle.repeatOnLifecycle import androidx.recyclerview.widget.LinearLayoutManager import com.google.android.material.dialog.MaterialAlertDialogBuilder import es.dmoral.toasty.Toasty import io.github.caimucheng.leaf.common.callback.FileCopyCallback import io.github.caimucheng.leaf.common.callback.FileSelectorCallback import io.github.caimucheng.leaf.common.fragment.FileCopyFragment import io.github.caimucheng.leaf.common.fragment.FileSelectorFragment import io.github.caimucheng.leaf.ide.R import io.github.caimucheng.leaf.ide.adapter.MainPluginAdapter import io.github.caimucheng.leaf.ide.databinding.FragmentMainPluginBinding import io.github.caimucheng.leaf.ide.model.Plugin import io.github.caimucheng.leaf.ide.model.name import io.github.caimucheng.leaf.ide.util.LeafIDEPluginRootPath import io.github.caimucheng.leaf.ide.viewmodel.AppIntent import io.github.caimucheng.leaf.ide.viewmodel.AppViewModel import io.github.caimucheng.leaf.ide.viewmodel.PluginState import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.collectLatest import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import java.io.File class MainPluginFragment : Fragment() { private lateinit var viewBinding: FragmentMainPluginBinding private val plugins by lazy { ArrayList<Plugin>(AppViewModel.state.value.plugins) } private val adapter by lazy { MainPluginAdapter( context = requireContext(), plugins = plugins, onToggle = { viewLifecycleOwner.lifecycleScope.launch { AppViewModel.intent.send(AppIntent.Refresh) } }, onUninstall = { showUninstallDialog(it) } ) } private fun showUninstallDialog(plugin: Plugin) { MaterialAlertDialogBuilder(requireContext()) .setTitle(plugin.name) .setIcon(plugin.icon) .setMessage(R.string.uninstall_plugin) .setNeutralButton(R.string.cancel, null) .setPositiveButton(R.string.sure) { _, _ -> viewLifecycleOwner.lifecycleScope.launch { AppViewModel.intent.send( AppIntent.Uninstall( plugin.packageName, requireContext(), childFragmentManager ) ) } }.show() } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { viewBinding = FragmentMainPluginBinding.inflate(inflater, container, false) return viewBinding.root } @SuppressLint("NotifyDataSetChanged") override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) setupToolbar() setupRecyclerView() viewLifecycleOwner.lifecycleScope.launch { repeatOnLifecycle(Lifecycle.State.STARTED) { AppViewModel.state.collectLatest { when (it.pluginState) { PluginState.Loading -> { viewBinding.content.visibility = View.GONE viewBinding.placeholder.visibility = View.GONE viewBinding.loading.visibility = View.VISIBLE } PluginState.Done -> { viewBinding.loading.visibility = View.GONE plugins.clear() plugins.addAll(it.plugins) adapter.notifyDataSetChanged() if (plugins.isNotEmpty()) { viewBinding.placeholder.visibility = View.GONE viewBinding.content.visibility = View.VISIBLE } else { viewBinding.content.visibility = View.GONE viewBinding.placeholder.visibility = View.VISIBLE } } } } } } } private fun setupToolbar() { viewBinding.toolbar.addMenuProvider(object : MenuProvider { override fun onCreateMenu(menu: Menu, menuInflater: MenuInflater) { menuInflater.inflate(R.menu.menu_main_plugin, menu) } override fun onMenuItemSelected(menuItem: MenuItem): Boolean { if (menuItem.itemId == R.id.installFromLocal) { showFileSelector() } return false } }, viewLifecycleOwner) } private fun showFileSelector() { val fileSelectorFragment = FileSelectorFragment() fileSelectorFragment.arguments = bundleOf( "matchingSuffix" to arrayListOf(".apk") ) fileSelectorFragment.setFileSelectorCallback(object : FileSelectorCallback { override fun onFileSelected(file: File) { fileSelectorFragment.dismiss() parsePluginDialog(file) } }) fileSelectorFragment.show(childFragmentManager, "installFromLocal") } private fun parsePluginDialog(file: File) { val packageManager = requireContext().packageManager val packageInfo = packageManager.getPackageArchiveInfo( file.absolutePath, PackageManager.GET_META_DATA ) if (packageInfo != null) { val application = packageInfo.applicationInfo application.sourceDir = file.absolutePath application.publicSourceDir = file.absolutePath val packageName = application.packageName showFileCopyDialog(file, packageName) } else { Toasty.error(requireContext(), R.string.unable_to_resolve_plugin, Toasty.LENGTH_LONG) .show() } } private fun showFileCopyDialog(file: File, packageName: String) { val fileCopyFragment = FileCopyFragment() fileCopyFragment.isCancelable = false fileCopyFragment.arguments = bundleOf( "name" to file.name, "from" to file.absolutePath, "to" to File(LeafIDEPluginRootPath, "${packageName}.apk").absolutePath, ) fileCopyFragment.setFileCopyCallback(object : FileCopyCallback { override fun onCopySuccess() { fileCopyFragment.dismiss() Toasty.success(requireContext(), R.string.copy_success, Toasty.LENGTH_SHORT) .show() installPlugin(packageName) } override fun onCopyFailed(e: Exception) { fileCopyFragment.dismiss() Toasty.error( requireContext(), getString(R.string.copy_failure, e.message), Toasty.LENGTH_LONG ).show() } }) fileCopyFragment.show(childFragmentManager, "fileCopy") } private fun installPlugin(packageName: String) { viewLifecycleOwner.lifecycleScope.launch { val plugin = withContext(Dispatchers.IO) { AppViewModel.state.value.plugins.find { it.packageName == packageName } } if (plugin != null) { AppViewModel.intent.send( AppIntent.Update( packageName, requireActivity(), childFragmentManager ) ) } else { AppViewModel.intent.send( AppIntent.Install( packageName, requireActivity(), childFragmentManager ) ) } } } private fun setupRecyclerView() { viewBinding.recyclerView.layoutManager = LinearLayoutManager(requireContext(), LinearLayoutManager.VERTICAL, false) viewBinding.recyclerView.adapter = adapter } }
LeafIDE/app/src/main/java/io/github/caimucheng/leaf/ide/fragment/main/MainPluginFragment.kt
2842799819
package io.github.caimucheng.leaf.ide.fragment.main import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import io.github.caimucheng.leaf.ide.databinding.FragmentMainSettingsBinding class MainSettingsFragment : Fragment() { private lateinit var viewBinding: FragmentMainSettingsBinding override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { viewBinding = FragmentMainSettingsBinding.inflate(inflater, container, false) return viewBinding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) } }
LeafIDE/app/src/main/java/io/github/caimucheng/leaf/ide/fragment/main/MainSettingsFragment.kt
3666287719
package io.github.caimucheng.leaf.ide.fragment import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import androidx.lifecycle.DefaultLifecycleObserver import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleEventObserver import androidx.lifecycle.LifecycleObserver import androidx.lifecycle.LifecycleOwner import androidx.lifecycle.lifecycleScope import androidx.navigation.fragment.NavHostFragment import androidx.navigation.ui.setupWithNavController import io.github.caimucheng.leaf.ide.R import io.github.caimucheng.leaf.ide.databinding.FragmentMainBinding import io.github.caimucheng.leaf.ide.viewmodel.AppIntent import io.github.caimucheng.leaf.ide.viewmodel.AppViewModel import io.github.caimucheng.leaf.ide.viewmodel.MainViewModel import kotlinx.coroutines.launch class MainFragment : Fragment() { private lateinit var viewBinding: FragmentMainBinding private val mainViewModel: MainViewModel by viewModels() override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { mainViewModel.initialize() viewBinding = FragmentMainBinding.inflate(inflater, container, false) return viewBinding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) setupBottomNavigation() if (!AppViewModel.state.value.isRefreshed) { viewLifecycleOwner.lifecycleScope.launch { AppViewModel.intent.send(AppIntent.Refresh) } } } private fun setupBottomNavigation() { val pageNavHostFragment = childFragmentManager.findFragmentById(R.id.fragmentContainerView) as NavHostFragment val pageNavController = pageNavHostFragment.navController viewBinding.bottomNavigationBar.setupWithNavController(pageNavController) } }
LeafIDE/app/src/main/java/io/github/caimucheng/leaf/ide/fragment/MainFragment.kt
1640890566
package io.github.caimucheng.leaf.ide.model import android.content.SharedPreferences import android.graphics.drawable.Drawable import androidx.core.content.edit import io.github.caimucheng.leaf.ide.application.AppContext import io.github.caimucheng.leaf.ide.depository.AppDepository import io.github.caimucheng.leaf.ide.depository.AppDepository.Companion.PLUGIN_MIN_VERSION import io.github.caimucheng.leaf.ide.util.launchModeSharedPreferences import io.github.caimucheng.leaf.ide.util.pluginSharedPreferences import io.github.caimucheng.leaf.plugin.PluginAPP data class Plugin( val icon: Drawable, val packageName: String, val versionName: String, val versionCode: Long, val entrance: String, val pluginMinVersion: Int, val pluginAPP: PluginAPP ) inline val Plugin.name: String get() { return pluginAPP.getPluginName() } inline val Plugin.description: String get() { return pluginAPP.getPluginDescription() } inline val Plugin.author: String get() { return pluginAPP.getPluginAuthor() } inline val Plugin.isSupported: Boolean get() { return pluginMinVersion >= PLUGIN_MIN_VERSION } inline val Plugin.isEnabled: Boolean get() { val pluginSharedPreferences = AppContext.current.pluginSharedPreferences return pluginSharedPreferences.getBoolean("${packageName}_isEnabled", true) } fun Plugin.enable() { val pluginSharedPreferences = AppContext.current.pluginSharedPreferences pluginSharedPreferences.edit { putBoolean("${packageName}_isEnabled", true) } } fun Plugin.disable() { val pluginSharedPreferences = AppContext.current.pluginSharedPreferences pluginSharedPreferences.edit { putBoolean("${packageName}_isEnabled", false) } } fun Plugin.toggle() { val pluginSharedPreferences = AppContext.current.pluginSharedPreferences val isEnabled = pluginSharedPreferences.getBoolean("${packageName}_isEnabled", true) pluginSharedPreferences.edit { putBoolean("${packageName}_isEnabled", !isEnabled) } }
LeafIDE/app/src/main/java/io/github/caimucheng/leaf/ide/model/Plugin.kt
964296865
package io.github.caimucheng.leaf.ide.model import org.json.JSONObject data class Project( val name: String, val description: String, val plugin: Plugin, val workspace: JSONObject )
LeafIDE/app/src/main/java/io/github/caimucheng/leaf/ide/model/Project.kt
4231827440
package io.github.caimucheng.leaf.ide.application import android.app.Application import android.content.BroadcastReceiver import android.content.Intent import android.content.IntentFilter import es.dmoral.toasty.Toasty import io.github.caimucheng.leaf.ide.broadcast.PluginBroadcastReceiver import io.github.caimucheng.leaf.ide.viewmodel.AppViewModel class AppContext : Application() { companion object { lateinit var current: AppContext private set lateinit var pluginBroadcastReceiver: BroadcastReceiver private set } override fun onCreate() { super.onCreate() current = this // Set default crash handler Thread.setDefaultUncaughtExceptionHandler(AppCrashHandler) Toasty.Config.getInstance() .allowQueue(false) .supportDarkTheme(true) .apply() pluginBroadcastReceiver = PluginBroadcastReceiver() // Register the broadcast val intentFilter = IntentFilter() intentFilter.addAction(Intent.ACTION_PACKAGE_ADDED) intentFilter.addAction(Intent.ACTION_PACKAGE_REPLACED) intentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED) intentFilter.addDataScheme("package") registerReceiver(pluginBroadcastReceiver, intentFilter) } override fun onTerminate() { AppViewModel.onCleared() unregisterReceiver(pluginBroadcastReceiver) super.onTerminate() } }
LeafIDE/app/src/main/java/io/github/caimucheng/leaf/ide/application/AppContext.kt
413724988
package io.github.caimucheng.leaf.ide.application import android.content.Intent import android.os.Build import android.os.Process import io.github.caimucheng.leaf.ide.activity.CrashHandlerActivity import kotlin.reflect.full.staticProperties import kotlin.reflect.jvm.isAccessible object AppCrashHandler : Thread.UncaughtExceptionHandler { override fun uncaughtException(t: Thread, e: Throwable) { e.printStackTrace() val deviceInfo = buildList { val buildClass = Build::class val buildMembers = buildClass.staticProperties for (member in buildMembers) { val name = member.name val value = member.get() add("$name: " + buildString { if (value is Array<*>) { append(value.fullToString()) } else { append(value) } }) } val buildVersionClass = Build.VERSION::class val buildVersionMembers = buildVersionClass.staticProperties for (member in buildVersionMembers) { member.isAccessible = true val name = member.name val value = member.get() add("$name: " + buildString { if (value is Array<*>) { append(value.fullToString()) } else { append(value) } }) } }.joinToString(separator = "\n") val context = AppContext.current context.startActivity(Intent(context, CrashHandlerActivity::class.java).apply { flags = Intent.FLAG_ACTIVITY_NEW_TASK putExtra("deviceInfo", deviceInfo) putExtra("threadGroup", t.threadGroup?.name ?: "null") putExtra("thread", t.name) putExtra("exception", e.stackTraceToString()) }) Process.killProcess(Process.myPid()) } private fun Array<*>.fullToString(): String { return buildString { append("[") for ((index, element) in [email protected]()) { if (element is Array<*>) { append(element.fullToString()) } else { append(element) } if (index + 1 < [email protected]) { append(", ") } } append("]") } } }
LeafIDE/app/src/main/java/io/github/caimucheng/leaf/ide/application/AppCrashHandler.kt
1706118305
package io.github.caimucheng.leaf.ide.broadcast import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.content.pm.PackageManager import android.util.Log import androidx.core.os.bundleOf import androidx.fragment.app.FragmentManager import androidx.lifecycle.DefaultLifecycleObserver import androidx.lifecycle.LifecycleOwner import io.github.caimucheng.leaf.common.callback.FileCopyCallback import io.github.caimucheng.leaf.common.fragment.FileCopyFragment import io.github.caimucheng.leaf.ide.activity.MainActivity import io.github.caimucheng.leaf.ide.util.LeafIDEPluginRootPath import io.github.caimucheng.leaf.ide.viewmodel.AppIntent import io.github.caimucheng.leaf.ide.viewmodel.AppViewModel import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CoroutineName import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.sync.Mutex import java.io.File import java.io.IOException import kotlin.coroutines.resume import kotlin.coroutines.resumeWithException import kotlin.coroutines.suspendCoroutine class PluginBroadcastReceiver : BroadcastReceiver() { companion object { private const val SKIP_PLUGIN_LIFECYCLE = true } private val coroutineScope = CoroutineScope(Dispatchers.Main + CoroutineName("PluginBroadcastCoroutine")) private val mutex = Mutex() override fun onReceive(context: Context, intent: Intent) { val extraReplacing = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false) val packageName = intent.dataString?.removePrefix("package:") ?: return when { !extraReplacing && intent.action == Intent.ACTION_PACKAGE_ADDED -> { Log.e("PluginBroadcast", "Package Added") debugInstallPlugin(context, packageName) } !extraReplacing && intent.action == Intent.ACTION_PACKAGE_REMOVED -> { Log.e("PluginBroadcast", "Package Removed") debugUninstallPlugin(packageName) } intent.action == Intent.ACTION_PACKAGE_REPLACED -> { Log.e("PluginBroadcastReceiver", "Package Replaced") debugUpdatePlugin(context, packageName) } } } private fun debugInstallPlugin(context: Context, packageName: String) { coroutineScope.launch { mutex.lock() try { val packageManager = context.packageManager val applicationInfo = packageManager.getApplicationInfo(packageName, PackageManager.GET_META_DATA) val metaData = applicationInfo.metaData ?: return@launch if (metaData.getBoolean("leafide_plugin", false)) { val activity = MainActivity.currentMainActivity?.get() ?: return@launch val fragmentManager = activity.supportFragmentManager copyFile(packageName, applicationInfo.sourceDir, fragmentManager, activity) AppViewModel.intent.send( AppIntent.Install( packageName, activity, fragmentManager, SKIP_PLUGIN_LIFECYCLE ) ) } } catch (e: Exception) { if (e is CancellationException) throw e e.printStackTrace() } finally { mutex.unlock() } } } private fun debugUninstallPlugin(packageName: String) { coroutineScope.launch { mutex.lock() try { if (AppViewModel.state.value.plugins.find { it.packageName == packageName } != null) { val activity = MainActivity.currentMainActivity?.get() ?: return@launch val fragmentManager = activity.supportFragmentManager deleteFile(packageName) AppViewModel.intent.send( AppIntent.Uninstall( packageName, activity, fragmentManager, SKIP_PLUGIN_LIFECYCLE ) ) } } catch (e: Exception) { if (e is CancellationException) throw e e.printStackTrace() } finally { mutex.unlock() } } } private fun debugUpdatePlugin(context: Context, packageName: String) { coroutineScope.launch { mutex.lock() try { val packageManager = context.packageManager val applicationInfo = packageManager.getApplicationInfo(packageName, PackageManager.GET_META_DATA) val metaData = applicationInfo.metaData ?: return@launch if (metaData.getBoolean("leafide_plugin", false)) { val activity = MainActivity.currentMainActivity?.get() ?: return@launch val fragmentManager = activity.supportFragmentManager copyFile(packageName, applicationInfo.sourceDir, fragmentManager, activity) AppViewModel.intent.send( AppIntent.Update( packageName, activity, fragmentManager, SKIP_PLUGIN_LIFECYCLE ) ) } } catch (e: Exception) { if (e is CancellationException) throw e e.printStackTrace() } finally { mutex.unlock() } } } private suspend fun deleteFile( packageName: String ) { suspendCoroutine { continuation -> if (File(LeafIDEPluginRootPath, "${packageName}.apk").delete()) { continuation.resume(Unit) } else { continuation.resumeWithException(IOException("Delete plugin failed")) } } } private suspend fun copyFile( packageName: String, sourceDir: String, fragmentManager: FragmentManager, activity: MainActivity ) { suspendCoroutine { continuation -> activity.lifecycle.addObserver(object : DefaultLifecycleObserver { override fun onStart(owner: LifecycleOwner) { activity.lifecycle.removeObserver(this) super.onStart(owner) val fileCopyFragment = FileCopyFragment() fileCopyFragment.arguments = bundleOf( "name" to packageName, "from" to sourceDir, "to" to File(LeafIDEPluginRootPath, "${packageName}.apk").absolutePath ) fileCopyFragment.setFileCopyCallback(object : FileCopyCallback { override fun onCopySuccess() { fileCopyFragment.dismiss() continuation.resume(Unit) } override fun onCopyFailed(e: Exception) { fileCopyFragment.dismiss() continuation.resumeWithException(e) } }) fileCopyFragment.isCancelable = false fileCopyFragment.show(fragmentManager, null) } }) } } }
LeafIDE/app/src/main/java/io/github/caimucheng/leaf/ide/broadcast/PluginBroadcastReceiver.kt
1750853674
package io.github.caimucheng.leaf.plugin.creator import io.github.caimucheng.leaf.plugin.fragment.PluginFragment interface FragmentCreator { fun onNewProject(): PluginFragment }
LeafIDE/plugin-api/src/main/java/io/github/caimucheng/leaf/plugin/creator/FragmentCreator.kt
3523638566
package io.github.caimucheng.leaf.plugin.path import java.io.File data class Paths( val externalRootPath: File, val leafIDEPluginRootPath: File, val leafIDERootPath: File, val leafIDEProjectPath: File )
LeafIDE/plugin-api/src/main/java/io/github/caimucheng/leaf/plugin/path/Paths.kt
422041784
package io.github.caimucheng.leaf.plugin import android.content.Context import android.content.ContextWrapper import android.content.res.Resources class PluginContext(base: Context?, private val resources: Resources) : ContextWrapper(base) { override fun getResources(): Resources { return resources } }
LeafIDE/plugin-api/src/main/java/io/github/caimucheng/leaf/plugin/PluginContext.kt
2110957528
package io.github.caimucheng.leaf.plugin import android.content.Context import android.content.res.Resources import android.graphics.drawable.Drawable import androidx.fragment.app.FragmentManager import io.github.caimucheng.leaf.plugin.creator.FragmentCreator import io.github.caimucheng.leaf.plugin.path.Paths abstract class PluginAPP { open fun onCreate(hostApplicationContext: Context, resources: Resources, paths: Paths) {} open suspend fun onInstall(activityContext: Context, fragmentManager: FragmentManager) {} open suspend fun onUninstall(activityContext: Context, fragmentManager: FragmentManager) {} open suspend fun onUpdate(activityContext: Context, fragmentManager: FragmentManager) {} abstract fun getFragmentCreator(): FragmentCreator abstract fun getPluginName(): String abstract fun getPluginDescription(): String abstract fun getPluginAuthor(): String abstract fun getProjectCardIcon(): Drawable abstract fun getProjectCardSubscript(): String abstract fun getTemplateIcon(): Drawable abstract fun getTemplateTitle(): String }
LeafIDE/plugin-api/src/main/java/io/github/caimucheng/leaf/plugin/PluginAPP.kt
63237197
package io.github.caimucheng.leaf.plugin.action import io.github.caimucheng.leaf.plugin.fragment.PluginFragment data class ActionHolder( private val onPopBackStack: () -> Unit, private val onPopBackHome: (Boolean) -> Unit, private val onStartFragment: (PluginFragment) -> Unit, private val onReplaceFragment: (PluginFragment) -> Unit ) { fun popBackStack() = onPopBackStack() fun popBackHome(refreshProject: Boolean = false) = onPopBackHome(refreshProject) fun startFragment(pluginFragment: PluginFragment) = onStartFragment(pluginFragment) fun replaceFragment(pluginFragment: PluginFragment) = onReplaceFragment(pluginFragment) }
LeafIDE/plugin-api/src/main/java/io/github/caimucheng/leaf/plugin/action/ActionHolder.kt
2435628448
package io.github.caimucheng.leaf.plugin.fragment import android.os.Bundle import android.view.View import androidx.annotation.CallSuper import androidx.fragment.app.Fragment import io.github.caimucheng.leaf.plugin.action.ActionHolder abstract class PluginFragment : Fragment() { protected lateinit var actionHolder: ActionHolder private set @CallSuper open fun onPrepareActionHolder(actionHolder: ActionHolder) { this.actionHolder = actionHolder } }
LeafIDE/plugin-api/src/main/java/io/github/caimucheng/leaf/plugin/fragment/PluginFragment.kt
858543673
import org.gradle.api.JavaVersion object Versions { const val versionName = "1.0.0.0" const val versionCode = 1 const val buildToolsVersion = "34.0.0" const val compileSdkVersion = 34 const val targetSdkVersion = 28 const val minSdkVersion = 21 val javaVersion = JavaVersion.VERSION_17 const val jvmToolchainVersion = 17 }
LeafIDE/build-logic/convention/src/main/kotlin/Versions.kt
3805553363
object NodeJSPluginVersions { const val VERSION_CODE = 1 const val VERSION_NAME = "Alpha v1.0" }
LeafIDE/build-logic/convention/src/main/kotlin/NodeJSPluginVersions.kt
528926909
package io.github.caimucheng.leaf.common.viewmodel import android.os.Environment import androidx.lifecycle.viewModelScope import io.github.caimucheng.leaf.common.depository.FileSelectorDepository import io.github.caimucheng.leaf.common.mvi.MVIViewModel import io.github.caimucheng.leaf.common.mvi.UiIntent import io.github.caimucheng.leaf.common.mvi.UiState import kotlinx.coroutines.launch import java.io.File enum class FileState { Loading, Done } data class FileSelectorState( val currentDirectory: File = Environment.getExternalStorageDirectory(), val fileState: FileState = FileState.Done, val files: List<File> = emptyList() ) : UiState() sealed class FileSelectorIntent : UiIntent() { data class Refresh(val matchingSuffix: List<String>?) : FileSelectorIntent() data class Enter(val targetDirectory: File, val matchingSuffix: List<String>?) : FileSelectorIntent() } class FileSelectorViewModel : MVIViewModel<FileSelectorState, FileSelectorIntent>() { private val fileSelectorDepository = FileSelectorDepository() override fun initialValue(): FileSelectorState { return FileSelectorState() } override fun handleIntent(intent: FileSelectorIntent, currentState: FileSelectorState) { when (intent) { is FileSelectorIntent.Refresh -> refresh(intent.matchingSuffix) is FileSelectorIntent.Enter -> enter(intent.targetDirectory, intent.matchingSuffix) } } private fun enter(targetDirectory: File, matchingSuffix: List<String>?) { viewModelScope.launch { setState(state.value.copy(fileState = FileState.Loading)) val files = fileSelectorDepository.enter(targetDirectory, matchingSuffix) setState( state.value.copy( fileState = FileState.Done, files = files, currentDirectory = targetDirectory ) ) } } private fun refresh(matchingSuffix: List<String>?) { viewModelScope.launch { setState(state.value.copy(fileState = FileState.Loading)) val files = fileSelectorDepository.refresh(state.value.currentDirectory, matchingSuffix) setState(state.value.copy(fileState = FileState.Done, files = files)) } } }
LeafIDE/common/src/main/java/io/github/caimucheng/leaf/common/viewmodel/FileSelectorViewModel.kt
3030845077
package io.github.caimucheng.leaf.common.viewmodel import android.content.res.AssetManager import androidx.lifecycle.viewModelScope import io.github.caimucheng.leaf.common.mvi.MVIViewModel import io.github.caimucheng.leaf.common.mvi.UiIntent import io.github.caimucheng.leaf.common.mvi.UiState import kotlinx.coroutines.CancellationException import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import java.io.File enum class FileCopyTotalState { UNSTARTED, PROCESSING, DONE, FAILED } data class FileCopyState( val name: String = "", val from: String = "", val to: String = "", val progress: Int = 0, val totalState: FileCopyTotalState = FileCopyTotalState.UNSTARTED, val exception: Exception? = null ) : UiState() sealed class FileCopyIntent : UiIntent() { data class Start(val name: String, val from: String, val to: String) : FileCopyIntent() data class StartFromAssets( val assets: AssetManager, val name: String, val from: String, val to: String, ) : FileCopyIntent() } class FileCopyViewModel : MVIViewModel<FileCopyState, FileCopyIntent>() { override fun initialValue(): FileCopyState { return FileCopyState() } override fun handleIntent(intent: FileCopyIntent, currentState: FileCopyState) { when (intent) { is FileCopyIntent.Start -> start(intent.name, intent.from, intent.to) is FileCopyIntent.StartFromAssets -> startFromAssets( intent.assets, intent.name, intent.from, intent.to ) } } private fun startFromAssets(assets: AssetManager, name: String, from: String, to: String) { viewModelScope.launch { setState( state.value.copy( name = name, from = from, to = to, totalState = FileCopyTotalState.PROCESSING ) ) try { startFromAssetsSuspend(assets, from, to) setState( state.value.copy( totalState = FileCopyTotalState.DONE ) ) } catch (e: Exception) { if (e is CancellationException) throw e setState(state.value.copy(totalState = FileCopyTotalState.FAILED, exception = e)) } } } private suspend fun startFromAssetsSuspend(assets: AssetManager, from: String, to: String) { return withContext(Dispatchers.IO) { processFile(assets, from, File(to)) } } private fun start(name: String, from: String, to: String) { viewModelScope.launch { setState( state.value.copy( name = name, from = from, to = to, totalState = FileCopyTotalState.PROCESSING ) ) try { startSuspend(from, to) setState( state.value.copy( totalState = FileCopyTotalState.DONE ) ) } catch (e: Exception) { if (e is CancellationException) throw e setState(state.value.copy(totalState = FileCopyTotalState.FAILED, exception = e)) } } } private suspend fun startSuspend(from: String, to: String) { return withContext(Dispatchers.IO) { val fromFile = File(from) val toFile = File(to) if (fromFile.isFile) { processFile(fromFile, toFile) } else { val folderSize = statisticsFolderSize(fromFile) processFolder( fromFile, toFile, ByteArray(8192), folderSize, 0L ) } } } private fun statisticsFolderSize(file: File): Long { var folderSize = 0L val children = file.listFiles() ?: emptyArray() for (child in children) { folderSize += if (child.isDirectory) { statisticsFolderSize(child) } else { child.length() } } return folderSize } private suspend fun processFolder( fromFile: File, toFile: File, buffer: ByteArray, folderSize: Long, transferred: Long ): Long { toFile.mkdirs() var currentTransferred = transferred val children = fromFile.listFiles() ?: emptyArray() for (child in children) { if (child.isDirectory) { currentTransferred = processFolder( child, File(toFile, child.name), buffer, folderSize, currentTransferred ) } else { val input = child.inputStream().buffered() val output = File(toFile, child.name).outputStream().buffered() input.use { _ -> output.use { _ -> var nRead: Int var tempProgress = 0 var progress: Int while (input.read(buffer, 0, buffer.size).also { nRead = it } >= 0) { output.write(buffer, 0, nRead) output.flush() currentTransferred += nRead.toLong() progress = (currentTransferred * 100L / folderSize).toInt() if (progress > tempProgress) { tempProgress = progress withContext(Dispatchers.Main) { setState(state.value.copy(progress = progress)) } } } } } } } return currentTransferred } private suspend fun processFile(fromFile: File, toFile: File) { val input = fromFile.inputStream().buffered() val output = toFile.outputStream().buffered() input.use { _ -> output.use { _ -> val fileSize = fromFile.length() val buffer = ByteArray(8192) var nRead: Int var transferred: Long = 0 var tempProgress = 0 var progress: Int while (input.read(buffer, 0, buffer.size).also { nRead = it } >= 0) { output.write(buffer, 0, nRead) output.flush() transferred += nRead.toLong() progress = (transferred * 100L / fileSize).toInt() if (progress > tempProgress) { tempProgress = progress withContext(Dispatchers.Main) { setState(state.value.copy(progress = progress)) } } } } } } private suspend fun processFile(assets: AssetManager, from: String, toFile: File) { val output = toFile.outputStream().buffered() val buffer = ByteArray(8192) var fileSize: Long = 0 assets.open(from).buffered().use { var nRead: Int while (it.read(buffer, 0, buffer.size).also { nRead = it } >= 0) { fileSize += nRead } } assets.open(from).buffered().use { input -> output.use { _ -> var nRead: Int var transferred: Long = 0 var tempProgress = 0 var progress: Int while (input.read(buffer, 0, buffer.size).also { nRead = it } >= 0) { output.write(buffer, 0, nRead) output.flush() transferred += nRead.toLong() progress = (transferred * 100L / fileSize).toInt() if (progress > tempProgress) { tempProgress = progress withContext(Dispatchers.Main) { setState(state.value.copy(progress = progress)) } } } } } } }
LeafIDE/common/src/main/java/io/github/caimucheng/leaf/common/viewmodel/FileCopyViewModel.kt
1529886852