Wanna make to search with using EditText when I click it from ListView. I made it with some youtube videos or blogs. Mixed up those and of course, There's error. What should fix? I put my every codes to understand it. Need you guys help a lot.
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Playbook">
<ListView
android:id="#+id/listView2"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:padding="16dp"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:layout_width="50dp"
android:layout_height="50dp"
android:src="#drawable/ic_baseline_search_24"
android:id="#+id/searchImage" />
<EditText
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_toRightOf="#id/searchImage"
android:id="#+id/editTextFilter"/>
<TextView
android:id="#+id/termName"
android:layout_marginLeft="20dp"
android:layout_marginTop="20dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/editTextFilter"
style="#style/TextAppearance.AppCompat.Title"
android:text="Term"/>
</RelativeLayout>
This is layout part.
package com.example.gridiron;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import java.util.ArrayList;
/**
* A simple {#link Fragment} subclass.
* Use the {#link Playbook#newInstance} factory method to
* create an instance of this fragment.
*/
public class Playbook extends Fragment {
ArrayList<PlaybookList> arrayList2;
ListView listView2;
private static PlaybookListAdapter playbookListAdapter;
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
public Playbook() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment Playbook.
*/
// TODO: Rename and change types and number of parameters
public static Playbook newInstance(String param1, String param2) {
Playbook fragment = new Playbook();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_playbook, container, false);
ListView listView2 = (ListView) view.findViewById(R.id.listView2);
EditText editTextFilter = (EditText) view.findViewById(R.id.editTextFilter);
ArrayList<PlaybookList> arrayList2 = new ArrayList<>();
arrayList2.add(new PlaybookList("Quarterback", "https://namu.wiki/w/%EC%BF%BC%ED%84%B0%EB%B0%B1"));
arrayList2.add(new PlaybookList("Runningback", "https://namu.wiki/w/%EB%9F%AC%EB%8B%9D%EB%B0%B1"));
PlaybookListAdapter playbookListAdapter = new PlaybookListAdapter(getActivity(), R.layout.list_row2, arrayList2);
listView2.setAdapter(playbookListAdapter);
editTextFilter.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable edit) {
String filterText = edit.toString();
if (filterText.length() > 0) {
listView2.setFilterText(filterText);
} else {
listView2.clearTextFilter();
}
}
});
listView2.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(String.valueOf(arrayList2.get(position).getTermURL())));
getActivity().startActivity(intent);
}
});
return view;
}
}
package com.example.gridiron;
public class PlaybookList {
String TermName;
String TermURL;
public PlaybookList(String termName, String termURL) {
TermName = termName;
TermURL = termURL;
}
public String getTermName() {
return TermName;
}
public void setTermName(String termName) {
TermName = termName;
}
public String getTermURL() {
return TermURL;
}
public void setTermURL(String termURL) {
TermURL = termURL;
}
}
package com.example.gridiron;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import java.util.ArrayList;
public class PlaybookListAdapter extends ArrayAdapter<PlaybookList> {
private Context mContext;
private int mResource;
public PlaybookListAdapter(#NonNull Context context, int resource, #NonNull ArrayList<PlaybookList> objects) {
super(context, resource, objects);
this.mContext = context;
this.mResource = resource;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
LayoutInflater layoutInflater = LayoutInflater.from(mContext);
convertView = layoutInflater.inflate(mResource, parent, false);
TextView termName = convertView.findViewById(R.id.termName);
termName.setText(getItem(position).getTermName());
return convertView;
}
}
And last 3 codes are for class. It's really hard to make it. Please, Help me!
There is no ListView in your layout code. You didn't include the error but I'm pretty sure it's NullPointerException on this line:
listView2.setAdapter(playbookListAdapter);
Related
I hope someone there will help me solve my problem. I have an Android application that uses the fragment. I want to download data using Volley from a JSON file. The program does not throw out any errors but CardView does not display with the ordered data. I looked at other topics with a similar problem, but I sit on it for a long time and nothing good happens.
AdapterZabytki.java
package eu.aisen.kamil.miejskiprzewodnik;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
import java.util.List;
import zabytki.Zabytki;
public class AdapterZabytki extends RecyclerView.Adapter<AdapterZabytki.ViewHolder> {
private List<Zabytek>list_data;
private Zabytki context;
public AdapterZabytki(List<Zabytek> list_data, Zabytki context) {
this.list_data = list_data;
this.context = context;
}
#Override
public AdapterZabytki.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
CardView view= (CardView) LayoutInflater.from(parent.getContext()).inflate(R.layout.obiectcard,parent,false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
Zabytek zabytek = list_data.get(position);
Picasso.get()
.load(zabytek
.getImage_url())
.into(holder.img);
holder.txtname.setText(zabytek.getName());
}
#Override
public int getItemCount() {
return list_data.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
private ImageView img;
private TextView txtname;
public ViewHolder(View view) {
super(view);
img=(ImageView)itemView.findViewById(R.id.info_image);
txtname=(TextView)itemView.findViewById(R.id.info_text);
}
}
}
Zabytek.java
package eu.aisen.kamil.miejskiprzewodnik;
public class Zabytek {
private String name;
private String image_url;
private String opis;
public Zabytek(String name, String image_url, String opis) {
this.name = name;
this.image_url = image_url;
this.opis = opis;
}
public String getName() {
return name;
}
public String getImage_url() {
return image_url;
}
public String getOpis() {
return opis;
}
}
Zabytki.java (fragment)
package zabytki;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import eu.aisen.kamil.miejskiprzewodnik.AdapterZabytki;
import eu.aisen.kamil.miejskiprzewodnik.R;
import eu.aisen.kamil.miejskiprzewodnik.Zabytek;
public class Zabytki extends Fragment {
private static final String HI = "https://wydzialedukacji.rzeszow.pl/testowy.json";
private ArrayList<Zabytek>list_data;
private AdapterZabytki mSensorAdapter;
private RecyclerView mRyclerView;
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container,
#Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.zabytki_fragment, container, false);
mRyclerView = view.findViewById(R.id.main_list);
mRyclerView.setHasFixedSize(true);
mRyclerView.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));
list_data = new ArrayList<>();
getData();
mSensorAdapter = new AdapterZabytki(list_data, this);
mRyclerView.setAdapter(mSensorAdapter);
mSensorAdapter.notifyDataSetChanged();
return view;
}
private void getData() {
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, HI, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("results");
for(int i=0; i < jsonArray.length(); i++){
JSONObject object = jsonArray.getJSONObject(i);
String name = object.getString("name");
String image_url = object.getString("image_url");
String opis = object.getString("opis");
list_data.add(new Zabytek(name, image_url, opis));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
Volley.newRequestQueue(getActivity()).add(request);
}
}
zabytki_fragment.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.RecyclerView android:id="#+id/main_list"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
</android.support.v7.widget.RecyclerView>
obiectcard.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"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="200dp"
android:id="#+id/card_view"
android:layout_margin="5dp"
card_view:cardCornerRadius="4dp">
<android.support.constraint.ConstraintLayout
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="16dp">
<ImageView
android:id="#+id/info_image"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_marginBottom="24dp"
android:layout_weight="1.0"
android:scaleType="centerCrop"
card_view:layout_constraintBottom_toBottomOf="parent"
card_view:srcCompat="#android:drawable/sym_def_app_icon"
tools:ignore="MissingConstraints" />
<TextView
android:id="#+id/info_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:layout_marginEnd="16dp"
android:text="tytułzabytku"
card_view:layout_constraintEnd_toEndOf="parent"
card_view:layout_constraintTop_toBottomOf="#+id/info_image" />
</android.support.constraint.ConstraintLayout>
</android.support.v7.widget.CardView>
I have 2 concerns about your code:
1. in onResponse, after you added all items to to list_data, you must call notifyDatasetChanged on RecyclerView adapter (AdapterZabytki)
2. Also, info_image in your ViewHolder seems to have zero height, because it has no top alignment and layout_height="0dp"
I am still wondering how to transfer this data to ZabytekDetailActivity.class
I have this:
mSensorAdapter.setListener(new AdapterZabytki.Listener() {
public void onClick(int position) {
ArrayList<Zabytek> object = new ArrayList<Zabytek>();
Intent intent = new Intent(getActivity(), ZabytekDetailActivity.class);
}
});
Now the question is how to attach the results from list_data so that they can be displayed in MonumentDetailActivity.class
I have created a sample app using the "Master / Detail flow" activity. I have added two buttons, Next and Prev to the detail activity. How to I set programmatically the buttons actions instead having to go back and forth between the List and detail?
item_detail.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingStart="30dp"
android:paddingEnd="30dp"
android:weightSum="4"
android:gravity="end"
android:orientation="horizontal">
<Button
android:id="#+id/button_prev"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Prev"/>
<Button
android:id="#+id/button_next"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Next"/>
</LinearLayout>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/item_detail"
style="?android:attr/textAppearanceLarge"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp"
android:textIsSelectable="true"
tools:context="co.test.app.sample.itemapplication.ItemDetailFragment"/>
</LinearLayout>
activity_item_detail.xml
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="co.test.app.sample.itemapplication.ItemDetailActivity"
tools:ignore="MergeRootFrame">
<android.support.design.widget.AppBarLayout
android:id="#+id/app_bar"
android:layout_width="match_parent"
android:layout_height="#dimen/app_bar_height"
android:fitsSystemWindows="true"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
<android.support.design.widget.CollapsingToolbarLayout
android:id="#+id/toolbar_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
app:contentScrim="?attr/colorPrimary"
app:layout_scrollFlags="scroll|exitUntilCollapsed"
app:toolbarId="#+id/toolbar">
<android.support.v7.widget.Toolbar
android:id="#+id/detail_toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:layout_collapseMode="pin"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"/>
</android.support.design.widget.CollapsingToolbarLayout>
</android.support.design.widget.AppBarLayout>
<android.support.v4.widget.NestedScrollView
android:id="#+id/item_detail_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior">
</android.support.v4.widget.NestedScrollView>
</android.support.design.widget.CoordinatorLayout>
DummyContent.java
package co.test.app.sample.itemapplication.dummy;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Helper class for providing sample content for user interfaces created by
* Android template wizards.
* <p>
* TODO: Replace all uses of this class before publishing your app.
*/
public class DummyContent {
/**
* An array of sample (dummy) items.
*/
public static final List<DummyItem> ITEMS = new ArrayList<DummyItem>();
/**
* A map of sample (dummy) items, by ID.
*/
public static final Map<String, DummyItem> ITEM_MAP = new HashMap<String, DummyItem>();
private static final int COUNT = 25;
static {
// Add some sample items.
for (int i = 1; i <= COUNT; i++) {
addItem(createDummyItem(i));
}
}
private static void addItem(DummyItem item) {
ITEMS.add(item);
ITEM_MAP.put(item.id, item);
}
private static DummyItem createDummyItem(int position) {
return new DummyItem(String.valueOf(position), "Item " + position, makeDetails(position));
}
private static String makeDetails(int position) {
StringBuilder builder = new StringBuilder();
builder.append("Details about Item: ").append(position);
for (int i = 0; i < position; i++) {
builder.append("\nMore details information here.");
}
return builder.toString();
}
/**
* A dummy item representing a piece of content.
*/
public static class DummyItem {
public final String id;
public final String content;
public final String details;
public DummyItem(String id, String content, String details) {
this.id = id;
this.content = content;
this.details = details;
}
#Override
public String toString() {
return content;
}
}
}
ItemDetailActivity.java
package co.test.app.sample.itemapplication;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.app.ActionBar;
import android.view.MenuItem;
/**
* An activity representing a single Item detail screen. This
* activity is only used narrow width devices. On tablet-size devices,
* item details are presented side-by-side with a list of items
* in a {#link ItemListActivity}.
*/
public class ItemDetailActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_item_detail);
Toolbar toolbar = (Toolbar) findViewById(R.id.detail_toolbar);
setSupportActionBar(toolbar);
// Show the Up button in the action bar.
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
}
// savedInstanceState is non-null when there is fragment state
// saved from previous configurations of this activity
// (e.g. when rotating the screen from portrait to landscape).
// In this case, the fragment will automatically be re-added
// to its container so we don't need to manually add it.
// For more information, see the Fragments API guide at:
//
// http://developer.android.com/guide/components/fragments.html
//
if (savedInstanceState == null) {
// Create the detail fragment and add it to the activity
// using a fragment transaction.
Bundle arguments = new Bundle();
arguments.putString(ItemDetailFragment.ARG_ITEM_ID,
getIntent().getStringExtra(ItemDetailFragment.ARG_ITEM_ID));
ItemDetailFragment fragment = new ItemDetailFragment();
fragment.setArguments(arguments);
getSupportFragmentManager().beginTransaction()
.add(R.id.item_detail_container, fragment)
.commit();
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
// This ID represents the Home or Up button. In the case of this
// activity, the Up button is shown. For
// more details, see the Navigation pattern on Android Design:
//
// http://developer.android.com/design/patterns/navigation.html#up-vs-back
//
navigateUpTo(new Intent(this, ItemListActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
}
ItemListActivity.java
package co.test.app.sample.itemapplication;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import co.test.app.sample.itemapplication.dummy.DummyContent;
import java.util.List;
/**
* An activity representing a list of Items. This activity
* has different presentations for handset and tablet-size devices. On
* handsets, the activity presents a list of items, which when touched,
* lead to a {#link ItemDetailActivity} representing
* item details. On tablets, the activity presents the list of items and
* item details side-by-side using two vertical panes.
*/
public class ItemListActivity extends AppCompatActivity {
/**
* Whether or not the activity is in two-pane mode, i.e. running on a tablet
* device.
*/
private boolean mTwoPane;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_item_list);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
toolbar.setTitle(getTitle());
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
View recyclerView = findViewById(R.id.item_list);
assert recyclerView != null;
setupRecyclerView((RecyclerView) recyclerView);
if (findViewById(R.id.item_detail_container) != null) {
// The detail container view will be present only in the
// large-screen layouts (res/values-w900dp).
// If this view is present, then the
// activity should be in two-pane mode.
mTwoPane = true;
}
}
private void setupRecyclerView(#NonNull RecyclerView recyclerView) {
recyclerView.setAdapter(new SimpleItemRecyclerViewAdapter(DummyContent.ITEMS));
}
public class SimpleItemRecyclerViewAdapter
extends RecyclerView.Adapter<SimpleItemRecyclerViewAdapter.ViewHolder> {
private final List<DummyContent.DummyItem> mValues;
public SimpleItemRecyclerViewAdapter(List<DummyContent.DummyItem> items) {
mValues = items;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_list_content, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(final ViewHolder holder, int position) {
holder.mItem = mValues.get(position);
holder.mIdView.setText(mValues.get(position).id);
holder.mContentView.setText(mValues.get(position).content);
holder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mTwoPane) {
Bundle arguments = new Bundle();
arguments.putString(ItemDetailFragment.ARG_ITEM_ID, holder.mItem.id);
ItemDetailFragment fragment = new ItemDetailFragment();
fragment.setArguments(arguments);
getSupportFragmentManager().beginTransaction()
.replace(R.id.item_detail_container, fragment)
.commit();
} else {
Context context = v.getContext();
Intent intent = new Intent(context, ItemDetailActivity.class);
intent.putExtra(ItemDetailFragment.ARG_ITEM_ID, holder.mItem.id);
context.startActivity(intent);
}
}
});
}
#Override
public int getItemCount() {
return mValues.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public final View mView;
public final TextView mIdView;
public final TextView mContentView;
public DummyContent.DummyItem mItem;
public ViewHolder(View view) {
super(view);
mView = view;
mIdView = (TextView) view.findViewById(R.id.id);
mContentView = (TextView) view.findViewById(R.id.content);
}
#Override
public String toString() {
return super.toString() + " '" + mContentView.getText() + "'";
}
}
}
}
This is the code snippet used to forward to the detail page.
if (mTwoPane) {
Bundle arguments = new Bundle();
arguments.putString(ItemDetailFragment.ARG_ITEM_ID, holder.mItem.id);
ItemDetailFragment fragment = new ItemDetailFragment();
fragment.setArguments(arguments);
getSupportFragmentManager().beginTransaction()
.replace(R.id.item_detail_container, fragment)
.commit();
} else {
Context context = v.getContext();
Intent intent = new Intent(context, ItemDetailActivity.class);
intent.putExtra(ItemDetailFragment.ARG_ITEM_ID, holder.mItem.id);
context.startActivity(intent);
}
You can forward to any page by changing the value of arguments.putString(ItemDetailFragment.ARG_ITEM_ID, holder.mItem.id);
Use the above snippets in the onClick events of next and prev buttons. cheers :)
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I'm trying to add a AutoCompleteTextView that will pull the location via GoogleApiClient.
I tried many different options to make that work and I get the following error:
Attempt to invoke virtual method 'void
com.google.android.gms.common.api.GoogleApiClient.connect()' on a null
object reference
Please tell me what I'm doing wrong, or suggest how to improve that.
Here is the XML code:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.freightos.priceestimator.MainActivity$ContainerFragment"
android:id="#+id/tabContainer">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="50dp"
android:gravity="center">
<AutoCompleteTextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/autocomplete"
android:drawableLeft="#drawable/location_icon_s"
android:drawablePadding="5dp"
android:hint="Type in your Location" />
</LinearLayout>
</LinearLayout>
And here is the ContainerFragment class:
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.ToggleButton;
import com.google.android.gms.common.api.PendingResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.location.places.Place;
import com.google.android.gms.location.places.PlaceBuffer;
import com.google.android.gms.location.places.Places;
import com.google.android.gms.location.places.ui.PlacePicker;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.LatLngBounds;
import org.w3c.dom.Text;
/**
* Created by Leonid on 6/30/2016.
*/
public class ContainerFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
// public Button btnCallAPI2;
public ContainerFragment() {
}
/**
* Returns a new instance of this fragment for the given section
* number.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
/*** Start Location Parameters *****/
private AutoCompleteTextView autocomplete;
private PlacePicker.IntentBuilder builder;
private PlacesAutoCompleteAdapter mPlacesAdapter;
private static final int PLACE_PICKER_FLAG = 1;
private static final LatLngBounds BOUNDS_GREATER_SYDNEY = new LatLngBounds(
new LatLng(-34.041458, 150.790100), new LatLng(-33.682247, 151.383362));
protected GoogleApiClient mGoogleApiClient;
/*** End Location Parameters *****/
public static ContainerFragment newInstance(int sectionNumber) {
ContainerFragment fragment = new ContainerFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.container_main, container, false);
/***** Start of Location Finder ****/
autocomplete = (AutoCompleteTextView) rootView.findViewById(R.id.autocomplete);
mPlacesAdapter = new PlacesAutoCompleteAdapter(this.getActivity(), android.R.layout.simple_list_item_1,mGoogleApiClient, BOUNDS_GREATER_SYDNEY, null);
autocomplete.setOnItemClickListener(mAutocompleteClickListener);
autocomplete.setAdapter(mPlacesAdapter);
/***** End of Location Finder ****/
return rootView;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
switch (requestCode) {
case PLACE_PICKER_FLAG:
Place place = PlacePicker.getPlace(data, this.getActivity());
autocomplete.setText(place.getName() + ", " + place.getAddress());
break;
}
}
}
#Override
public void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
#Override
public void onStop() {
mGoogleApiClient.disconnect();
super.onStop();
}
private AdapterView.OnItemClickListener mAutocompleteClickListener
= new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
final PlacesAutoCompleteAdapter.PlaceAutocomplete item = mPlacesAdapter.getItem(position);
final String placeId = String.valueOf(item.placeId);
PendingResult<PlaceBuffer> placeResult = Places.GeoDataApi
.getPlaceById(mGoogleApiClient, placeId);
placeResult.setResultCallback(mUpdatePlaceDetailsCallback);
}
};
private ResultCallback<PlaceBuffer> mUpdatePlaceDetailsCallback
= new ResultCallback<PlaceBuffer>() {
#Override
public void onResult(PlaceBuffer places) {
if (!places.getStatus().isSuccess()) {
Log.e("place", "Place query did not complete. Error: " +
places.getStatus().toString());
return;
}
// Selecting the first object buffer.
final Place place = places.get(0);
}
};
}
You haven't initialised mGoogleApiClient object. Please do the following:
protected void onCreate(Bundle savedInstanceState){
.....
// First we need to check availability of play services
if (checkPlayServices()) {
// Building the GoogleApi client
buildGoogleApiClient();
}
....
}
checkPlayServices method:
private boolean checkPlayServices() {
int resultCode = GooglePlayServicesUtil
.isGooglePlayServicesAvailable(this);
if (resultCode != ConnectionResult.SUCCESS) {
if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
GooglePlayServicesUtil.getErrorDialog(resultCode, this,
PLAY_SERVICES_RESOLUTION_REQUEST).show();
} else {
Toast.makeText(getApplicationContext(),
"This device is not supported.", Toast.LENGTH_LONG)
.show();
finish();
}
return false;
}
return true;
}
buildGoogleApiClient method:
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API).build();
}
please check out the following link for complete code: source
So I was trying to make a listview inside the fragment, although the code works, this list itself looks wierd. Here's a picture of it.
I'd appreciate your help in figuring out why the list looks strange.
ussd.java (Fragment)
package layout;
import android.app.Activity;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import com.buckydroid.app.droidcpu.R;
import com.buckydroid.app.droidcpu.ussdadaper;
import com.buckydroid.app.droidcpu.ussdz;
import com.google.android.gms.tagmanager.Container;
import java.util.ArrayList;
import java.util.List;
/**
* A simple {#link Fragment} subclass.
* Activities that contain this fragment must implement the
* {#link ussd.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {#link ussd#newInstance} factory method to
* create an instance of this fragment.
*/
public class ussd extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private ListView listView;
private ussdadaper ussd;
private List<ussdz> ussdlist;
private OnFragmentInteractionListener mListener;
public ussd() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment ussd.
*/
// TODO: Rename and change types and number of parameters
public static ussd newInstance(String param1, String param2) {
ussd fragment = new ussd();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView( LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState )
{
View rootView = inflater.inflate(R.layout.fragment_ussd, container, false);
listView = (ListView)rootView.findViewById(R.id.listView);
ussdlist = new ArrayList<>();
ussdlist.add(new ussdz("*#44336#","Software Version Info"));
ussdlist.add(new ussdz("*#44336#","Software Version Info"));
ussdlist.add(new ussdz("*#44336#","Software Version Info"));
ussdlist.add(new ussdz("*#44336#","Software Version Info"));
ussdlist.add(new ussdz("*#44336#","Software Version Info"));
ussdlist.add(new ussdz("*#44336#","Software Version Info"));
ussdlist.add(new ussdz("*#44336#","Software Version Info"));
ussdlist.add(new ussdz("*#44336#","Software Version Info"));
ussd = new ussdadaper(getActivity(),ussdlist);
listView .setAdapter(ussd); //you should setthe adapter to the listview
return rootView;
}
// TODO: Rename method, update argument and hook method into UI event
#Override
public void onAttach(Context context) {
super.onAttach(context);
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
public void onFragmentInteractionHome(Uri uri);
public void openHome(View view);
}
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p/>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
Adapter
package com.buckydroid.app.droidcpu;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import java.util.List;
/**
* Created by BuckyDroid on 14-06-2016.
*/
public class ussdadaper extends BaseAdapter {
private Context ussds;
private List<ussdz> ussdlist;
public ussdadaper(Context ussds, List<ussdz> ussdlist) {
this.ussds = ussds;
this.ussdlist = ussdlist;
}
#Override
public int getCount() {
return ussdlist.size();
}
#Override
public Object getItem(int position) {
return ussdlist.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v= View.inflate(ussds,R.layout.item_listview,null);
TextView ussdcode = (TextView)v.findViewById(R.id.textView1);
TextView ussddesc = (TextView)v.findViewById(R.id.textView2);
ussdcode.setText(ussdlist.get(position).getUSSD());
ussddesc.setText(ussdlist.get(position).getDescription());
return v;
}
}
ussdz.java
package com.buckydroid.app.droidcpu;
/**
* Created by BuckyDroid on 14-06-2016.
*/
public class ussdz
{
private int id;
private String USSD;
private String Description;
public ussdz(String description, String s) {
Description = description;
this.USSD = USSD;
this.id = id;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUSSD() {
return USSD;
}
public void setUSSD(String USSD) {
this.USSD = USSD;
}
public String getDescription() {
return Description;
}
public void setDescription(String description) {
Description = description;
}
}
item_listview.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#android:color/transparent"
android:paddingLeft="5dp"
android:paddingRight="5dp"
android:orientation="vertical"
>
<LinearLayout
android:id="#+id/lyt"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:minHeight="1px"
android:gravity="left|top"
android:padding="2dp"
android:orientation="horizontal" >
<TextView
android:id="#+id/textView1"
android:layout_width="0dp"
android:layout_weight="5"
android:layout_height="wrap_content"
android:textColor="#color/darker_grey"
android:gravity="left|top"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Name"
android:textStyle="bold"/>
<TextView
android:gravity="left|top"
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:layout_height="wrap_content"
android:textColor="#color/darker_grey"
android:paddingLeft="5dp"
android:paddingRight="10dp"
android:text=":" />
<TextView
android:textStyle="bold"
android:gravity="left|top"
android:id="#+id/textView2"
android:layout_width="0dp"
android:layout_weight="6"
android:layout_height="wrap_content"
android:textColor="#color/darker_grey"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Medium Text"/>
</LinearLayout>
</LinearLayout>
Update:
fragment's xml file
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="layout.ussd">
<!-- TODO: Update blank fragment layout -->
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/listView"
android:layout_gravity="center" />
</FrameLayout>
In your ussdz object your are not settign the USSD:
public ussdz(String description, String s) {
Description = description;
this.USSD = USSD; //No need to do that, it will be still null
this.id = id; //No need to do that, it will be still null
}
so you can add the SDD value in constructor:
private int id;
private String USSD;
private String description;
public ussdz(int mId, String mDescription, String mUSSD) {
description = mDescription;
this.USSD = mUSSD;
this.id = mId;
}
And construct an object like:
ussdz myObject = new ussdz(1, "description", "4529697");
I'm currently using a method made by Prabeesh R K from YouTube. I'm currently following all the steps without a miss, and I'm only modifying it a little, but the problem is the RecyclerView in my phone is not showing anything. Moreover, there is an error in log : E/RecyclerView: No adapter attached; skipping layout. Can you please help me resolve this. By the way this is my code
GenreView.java (Activity)
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import java.util.ArrayList;
/**
* Created by A46CB on 2/21/2016.
*/
public class GenreView extends AppCompatActivity{
RecyclerView rvgenre;
GenreAdapter adaptergenre;
RecyclerView.LayoutManager genrelayoutmanager;
String[] judulgenre;
int []imgres = {R.drawable.w06, R.drawable.w100, R.drawable.w102, R.drawable.w144, R.drawable.w173,
R.drawable.w179, R.drawable.w182, R.drawable.w36, R.drawable.w77, R.drawable.w79, R.drawable.w93,
R.drawable.w97};
ArrayList<GenreContent> arrayList = new ArrayList<GenreContent>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tab_genre);
rvgenre = (RecyclerView)findViewById(R.id.genre_recycler_view);
rvgenre.setHasFixedSize(true);
judulgenre = getResources().getStringArray(R.array.genre_title);
int i = 0;
for(String name : judulgenre)
{
GenreContent genrecontent = new GenreContent(imgres[i],judulgenre[i]);
arrayList.add(genrecontent);
i++;
}
genrelayoutmanager = new GridLayoutManager(this, 2);
rvgenre.setLayoutManager(genrelayoutmanager);
adaptergenre = new GenreAdapter(arrayList);
rvgenre.setAdapter(adaptergenre);
}
}
GenreAdapter.Java (Adapter)
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
/**
* Created by A46CB on 2/21/2016.
*/
public class GenreAdapter extends RecyclerView.Adapter<GenreAdapter.GenreRecyclerViewHolder> {
private ArrayList<GenreContent> arrayList = new ArrayList<GenreContent>();
public GenreAdapter(ArrayList<GenreContent> arrayList)
{
this.arrayList = arrayList;
}
#Override
public GenreRecyclerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.genre_layout, parent, false);
GenreRecyclerViewHolder grvh = new GenreRecyclerViewHolder(view);
return grvh;
}
#Override
public void onBindViewHolder(GenreRecyclerViewHolder holder, int position) {
GenreContent genreContent = arrayList.get(position);
holder.imgView.setImageResource(genreContent.getImg());
holder.tvgenre.setText(genreContent.getTitle());
}
#Override
public int getItemCount() {
return arrayList.size();
}
public static class GenreRecyclerViewHolder extends RecyclerView.ViewHolder {
ImageView imgView;
TextView tvgenre;
public GenreRecyclerViewHolder (View view){
super (view);
imgView = (ImageView)view.findViewById(R.id.genrepic);
tvgenre = (TextView)view.findViewById(R.id.titlegenre);
}
}
}
GenreContent.java
public class GenreContent {
private int img;
private String title;
public GenreContent(int img, String title){
this.setImg(img);
this.setTitle(title);
}
public int getImg() {
return img;
}
public void setImg(int img) {
this.img = img;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
My Layout
TabGenre.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.RecyclerView
android:id="#+id/genre_recycler_view"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
GenreLayout.xml (Custom Layout)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="6dip"
android:orientation="vertical">
<ImageView
android:layout_width="160dp"
android:layout_height="120dp"
android:src="#drawable/bgheader"
android:id="#+id/genrepic"/>
<TextView
android:id="#+id/titlegenre"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Mystery"
android:layout_marginTop="-5dp"
android:layout_gravity="center_horizontal"/>
</LinearLayout>
You should change this line
adaptergenre = new GenreAdapter(new ArrayList<>(arrayList));
to
adaptergenre = new GenreAdapter(arrayList);
There is new need to create new ArrayList