Particular Title(Fetched from API) Using Searchview

particular title(fetched from api) using searchview?

You can achieve suggestions related to your search query using recyclerview and adapters.

[1] Create new adapter and put your setMovieList() and getFilter() into it.

[2] Set that adapter into recyclerview of suggestions and notify adapter when you get your arraylist of suggestions.

check below code

public void onResponse(retrofit2.Call<List<StartLearning.SlModel>> call, Response<List<StartLearning.SlModel>> response) {

movieList = response.body();
if(movieList.size()!=0){
tvSuggestions.setVisibility(View.VISIBLE);
suggestionAdapter=new SuggestionAdapter(Search.this,movieList);
recyclerViewSuggestions.setAdapter(suggestionAdapter);
Log.e("TAG", "onResponse: size of movielist "+movieList);
suggestionAdapter.getFilter().filter(query);
suggestionAdapter.notifyDataSetChanged();
suggestionAdapter.setMovieList(Search.this,movieList);

}
else{
tvSuggestions.setVisibility(View.VISIBLE);
tvSuggestions.setText("No Suggestions Found");
}

/*generateDataList(movieList);
Log.d("TAG","Response = "+movieList);
slAdapter.setMovieList(getApplicationContext(),movieList);*/

}

how to display data of different api ids to different items of recycle view?

As far I understand what you want to do, according to that I assume that you need following changes:

In WhatsAndroidAdapter

view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(context, NextActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra("title", WAmdel.get(getAdapterPosition()).getTitle());
intent.putExtra("id", WAmdel.get(getAdapterPosition()).getId());

context.startActivity(intent);

}
});

In NextActivity

Intent intent = getIntent();
String title = intent.getStringExtra("title");
String id = intent.getStringExtra("id");
String hello=intent.getStringExtra("hii");

getSupportActionBar().setTitle(title);
/*Create handle for the RetrofitInstance interface*/
DescriptService service = DescriptClientInstance.getRetrofitInstance().create(DescriptService.class);
Call<DescriptionModel> call = service.getAllPhotos(id);
call.enqueue(new Callback<DescriptionModel>() {
@Override
public void onResponse(Call<DescriptionModel> call, Response<DescriptionModel> response) {
// progressDialog.dismiss();
DescriptList=response.body();
generateDataList(DescriptList);
}

@Override
public void onFailure(Call<DescriptionModel> call, Throwable t) {
// progressDialog.dismiss();

Toast.makeText(getApplicationContext(), "Something went wrong...Please try later!", Toast.LENGTH_SHORT).show();
}
});

In DescriptService

@GET("/v1/android_tutorials/single_tutorial") 
Call<DescriptionModel> getAllPhotos(@Query("tutorial_id") String id);

SearchView query hint before clicking it

Use this XML:

android:queryHint="hint"
app:queryHint="hint"
app:defaultQueryHint="hint"
android:iconifiedByDefault="false" // this line
app:iconifiedByDefault="false"

app used for {android.support.v7.widget.SearchView}

How to implement AutoCompleteTextView within onQueryTextChange function of SearchView in actionbar

EDITED

The Layout file, named activity_search.xml.

<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/nested_parentframe"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/transparent">

<!-- HERE IS WHERE YOUR OTHER VIEWS SHOULD GO -->

<android.support.v7.widget.Toolbar
android:id="@+id/nested_toolbar_1"
android:layout_width="match_parent"
android:layout_height="56dp"
android:background="#ffffff" />

<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="0dp"
app:cardBackgroundColor="@android:color/transparent"
app:cardElevation="0dp">

<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_margin="5dp"
android:layout_gravity="center"
android:background="#ffffff">

<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#ffffff"
app:cardElevation="0dp"
app:cardPreventCornerOverlap="false">

<android.support.v7.widget.Toolbar
android:id="@+id/nested_toolbar_2"
android:layout_width="match_parent"
android:layout_height="56dp"
android:layout_marginTop="0dp"
android:layout_gravity="center" />

</android.support.v7.widget.CardView>

</LinearLayout>

</android.support.v7.widget.CardView>

<LinearLayout
android:id="@+id/recyclerViewLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center_horizontal"
android:layout_marginBottom="5dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:background="#ffffff"
android:orientation="vertical"
android:visibility="gone">

<android.support.v7.widget.RecyclerView
android:id="@+id/cardsList"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:dividerHeight="1dp"/>
</LinearLayout>

</LinearLayout>

</FrameLayout>

Here is the Menu where SearchView is placed, named search_menu.xml.

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools">

<item
android:id="@+id/search_menu_item"
android:icon="@drawable/ic_search_grey"
app:showAsAction="always|collapseActionView"
app:actionViewClass="yourpackage.ArrayAdapterSearchView"
android:textSize="16sp"
android:title="Search" />
</menu>

Here is a custom ArrayAdapter for the SearchView.

public class ArrayAdapterSearchView extends SearchView {

private SearchView.SearchAutoComplete mSearchAutoComplete;

public ArrayAdapterSearchView(Context context) {
super(context);
initialize();
}

public ArrayAdapterSearchView(Context context, AttributeSet attrs) {
super(context, attrs);
initialize();
}

public void initialize() {
mSearchAutoComplete = (SearchAutoComplete) findViewById(android.support.v7.appcompat.R.id.search_src_text);
this.setAdapter(null);
this.setOnItemClickListener(null);
}

@Override
public void setSuggestionsAdapter(CursorAdapter adapter) {
// don't let anyone touch this
}

public void setOnItemClickListener(AdapterView.OnItemClickListener listener) {
mSearchAutoComplete.setOnItemClickListener(listener);
}

public void setAdapter(ArrayAdapter<?> adapter) {
mSearchAutoComplete.setAdapter(adapter);
}

public void setText(String text) {
mSearchAutoComplete.setText(text);
}

public void setSelection(int position){
mSearchAutoComplete.setSelection(position);
}

public String getText(){
return mSearchAutoComplete.getText().toString();
}
}

Here is the RecyclerView list item layout, named card_item.xml.

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
card_view:cardCornerRadius="1dp">

<TextView
android:id="@+id/itemNametxt"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="left"
android:text=""
android:textStyle="normal" />

</android.support.v7.widget.CardView>

Inside your Custom Adapter write a function like this.

public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter .CustomRecyclerHolder> {
private Context context;
private ArrayList<String> arrayList = null, stringArrayList;
private OnItemClickListener listener;

public CustomAdapter(Context context, ArrayList<String> items) {
this.context = context;
this.arrayList = items;
this.stringArrayList = new ArrayList<String>();
this.stringArrayList.addAll(items);
}

@Override
public CustomAdapter.CustomRecyclerHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.card_item, parent, false);

return new CustomRecyclerHolder(itemView);
}

@Override
public void onBindViewHolder(CustomAdapter.CustomRecyclerHolder holder, int position) {
holder.item.setText(arrayList.get(position).toString());
}

public class CustomRecyclerHolder extends RecyclerView.ViewHolder{
protected TextView item;

public CustomRecyclerHolder(View v){
super(v);
item = (TextView) v.findViewById(R.id.itemNametxt);

v.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (listener != null) {
listener.onItemClick(item.getText().toString());
}
}
});
}
}

@Override
public int getItemCount() {
return this.arrayList.size();
}

public void filter(String filterString) {
filterString = filterString.toLowerCase(Locale.getDefault());
arrayList.clear();//Your list of items
if(filterString.length() == 0) {
arrayList.addAll(stringArrayList);
//stringArrayList - 2nd list of items
}
else {
for(String item : stringArrayList){
if(item.toLowerCase(Locale.getDefault()).contains(filterString)) {
arrayList.add(item );
}
}
}
notifyDataSetChanged();
}

public void setOnItemClickListener(OnItemClickListener listener){
this.listener = listener;
}

public interface OnItemClickListener{
public void onItemClick(String item);
}
}

Finally the Activity.
EDITED

public class ExampleActivity extends AppCompatActivity {

private ArrayAdapterSearchView searchView;
private LinearLayout recycleLayout;
private ArrayList<String> stringList;
private RecyclerView recyclerView;
private CustomAdapter adapter;
private Toolbar mToolbar1, mToolbar2;
private FrameLayout frameLayout;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);

mToolbar1 = (Toolbar) findViewById(R.id.nested_toolbar_1);
mToolbar2 = (Toolbar) findViewById(R.id.nested_toolbar_2);

frameLayout = (FrameLayout) findViewById(R.id.nested_parentframe);

setSupportActionBar(mToolbar2);
getSupportActionBar().setTitle("Search");
mToolbar1.setNavigationIcon(R.mipmap.ic_action_overflow);

mToolbar2.setTitleTextColor(getResources().getColor(android.R.color.tertiary_text_light));

recycleLayout = (LinearLayout) findViewById(R.id.recyclerViewLayout);

recyclerView = (RecyclerView) findViewById(R.id.cardsList);
recyclerView.setHasFixedSize(true);
LinearLayoutManager llm = new LinearLayoutManager(this);
llm.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView.setLayoutManager(llm);

getSupportActionBar().setDisplayShowHomeEnabled(true);

String[] strArray = new String[]{"Item One", "Item Two", "Item Three", "Item Four", "Item Five"};
//This is your String array
for(int i = 0; i < strArray.length; i++){
stringList.add(strArray[i]);
}

if(!stringList.isEmpty()){
adapter = new CustomAdapter(this, stringList);
recyclerView.setAdapter(adapter);

recycleLayout.setVisibility(View.VISIBLE);

adapter.setOnItemClickListener(new CustomAdapter.OnItemClickListener() {
@Override
public void onItemClick(String item) {
searchView.setQuery(item, false);
}
});
}
else{
recycleLayout.setVisibility(View.GONE);
}

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.search_menu, menu);

MenuItem searchItem = menu.findItem(R.id.search_menu_item);

searchView = (ArrayAdapterSearchView) MenuItemCompat.getActionView(searchItem);
searchView.setLayoutParams(new ActionBar.LayoutParams(Gravity.LEFT));

searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
return false;
}

@Override
public boolean onQueryTextChange(String query) {
if (query.length() != 0) {
if (null != adapter) {
adapter.filter(query.toString());//This will filter the RecyclerView
recyclerView.setVisibility(View.VISIBLE);
}
}
else{
recyclerView.setVisibility(View.GONE);
}
return false;
}
});

searchView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String length = searchView.getText();
searchView.setSelection(length.length());
}
});

return true;
}

}

Is there a way to modify fetched results with a predicate after they are initialized?

Is there a way to modify fetched results with a predicate after they
are initialized?

Well... no, not in the way you try to do this, and even if you'd try to create it with NSFetchRequest instance, which is reference, and allows to change predicate later, that wouldn't work, because SwiftUI's FetchRequest stores copy of provided fetch request (or creates own with provided parameters)... so, no. But...

You can break apart view providing fetch request parameters with view constructing fetch request and showing result.

Here is a demo of approach (important part of it) which gives you possibility to get results with different dynamically changed predicates:

struct MasterView: View {
@State var predicate: NSPredicate? = nil
var body: some View {
VStack {
Button(action: { // button just for demo
self.predicate = NSPredicate(format: "title contains[c] %@", "h")
}, label: { Text("Filter") })
ResultView(predicate: self.predicate)
}
}
}

struct ResultView: View {

@FetchRequest
var events: FetchedResults<Event>

@Environment(\.managedObjectContext)
var viewContext

init(predicate: NSPredicate?) {
let request: NSFetchRequest<Event> = Event.fetchRequest()
request.sortDescriptors = [NSSortDescriptor(keyPath: \Event.timestamp, ascending: true)]
if let predicate = predicate {
request.predicate = predicate
}
_events = FetchRequest<Event>(fetchRequest: request)
}

var body: some View {
List {
ForEach(events, id: \.self) { event in
...

how to search from data in api [flutter]

Try below answer hope its helpful to you.

//declare packages
import 'dart:async';
import 'dart:convert';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

class Jobs extends StatefulWidget {
Jobs() : super();

@override
JobsState createState() => JobsState();
}

class Debouncer {
int? milliseconds;
VoidCallback? action;
Timer? timer;

run(VoidCallback action) {
if (null != timer) {
timer!.cancel();
}
timer = Timer(
Duration(milliseconds: Duration.millisecondsPerSecond),
action,
);
}
}

class JobsState extends State<Jobs> {
final _debouncer = Debouncer();

List<Subject> ulist = [];
List<Subject> userLists = [];
//API call for All Subject List

String url = 'https://type.fit/api/quotes';

Future<List<Subject>> getAllulistList() async {
try {
final response = await http.get(Uri.parse(url));
if (response.statusCode == 200) {
// print(response.body);
List<Subject> list = parseAgents(response.body);
return list;
} else {
throw Exception('Error');
}
} catch (e) {
throw Exception(e.toString());
}
}

static List<Subject> parseAgents(String responseBody) {
final parsed = json.decode(responseBody).cast<Map<String, dynamic>>();
return parsed.map<Subject>((json) => Subject.fromJson(json)).toList();
}

@override
void initState() {
super.initState();
getAllulistList().then((subjectFromServer) {
setState(() {
ulist = subjectFromServer;
userLists = ulist;
});
});
}

//Main Widget
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(
'All Users',
style: TextStyle(fontSize: 25),
),
),
body: Column(
children: <Widget>[
//Search Bar to List of typed Subject
Container(
padding: EdgeInsets.all(15),
child: TextField(
textInputAction: TextInputAction.search,
decoration: InputDecoration(
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(25.0),
borderSide: BorderSide(
color: Colors.grey,
),
),
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(20.0),
borderSide: BorderSide(
color: Colors.blue,
),
),
suffixIcon: InkWell(
child: Icon(Icons.search),
),
contentPadding: EdgeInsets.all(15.0),
hintText: 'Search ',
),
onChanged: (string) {
_debouncer.run(() {
setState(() {
userLists = ulist
.where(
(u) => (u.text.toLowerCase().contains(
string.toLowerCase(),
)),
)
.toList();
});
});
},
),
),
Expanded(
child: ListView.builder(
shrinkWrap: true,
physics: ClampingScrollPhysics(),
padding: EdgeInsets.all(5),
itemCount: userLists.length,
itemBuilder: (BuildContext context, int index) {
return Card(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20),
side: BorderSide(
color: Colors.grey.shade300,
),
),
child: Padding(
padding: EdgeInsets.all(5.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
ListTile(
title: Text(
userLists[index].text,
style: TextStyle(fontSize: 16),
),
subtitle: Text(
userLists[index].author ?? "null",
style: TextStyle(fontSize: 16),
),
)
],
),
),
);
},
),
),
],
),
);
}
}

//Declare Subject class for json data or parameters of json string/data
//Class For Subject
class Subject {
var text;
var author;
Subject({
required this.text,
required this.author,
});

factory Subject.fromJson(Map<dynamic, dynamic> json) {
return Subject(
text: json['text'],
author: json['author'],
);
}
}

Your result screen before search -> Sample Image

Your result screen after search -> Sample Image

data is not getting displayed in retrofit

Might be i got the problem.
Problem is here @GET("/v1/android_tutorials/single_advance?") you have? in the end of your url and you also have @Query("advance_id") field that mean your request contain two ?. you request currently look like this.

/v1/android_tutorials/single_advance??advance_id="xxxx"

Remember when you add @Query("advance_id") to your request this by default add ? to your your. So remove? from your url end. Your url should look like this

 @GET("/v1/android_tutorials/single_advance")


Related Topics



Leave a reply



Submit