Is there a way to choose a specific row of my RecyclerView (maybe by getting the index of the row) and then use it to create an intent.
I tried some things by getting the specific row information but that was not even close. My recycler is populated with data from a database.
To choose a specific row of my recycler, you can add setOnItemClickListener code like this one to your onCreate function:
listView_search.setOnItemClickListener(
new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id){
//Here I'm getting store_id and store_name
TextView store_search_id =(TextView) v.findViewById(R.id.store_search_id);
TextView store_search_name =(TextView) v.findViewById(R.id.store_search_name);
String store_name = store_search_name.getText().toString();
String store_id = store_search_id.getText().toString();
//Then I'm sending theses variables to a shared Intent
Intent myIntent = new Intent(getApplicationContext(), StoresShowActivity.class);
myIntent.putExtra("STORE_ID", store_id);
myIntent.putExtra("STORE_NAME", store_name);
startActivity(myIntent);
}
}
);
You may also want to follow these steps:
A. Add a layout for the Recycle view:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_stores_search"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="ksa.ikp.activities.StoresSearchActivity">
<SearchView
android:id="#+id/SearchView_store"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:iconifiedByDefault="false">
<requestFocus />
</SearchView>
<ListView
android:id="#+id/listView_search"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_below="#+id/SearchView_store" />
</RelativeLayout >
B. Add a layout for the recycleview item
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal"
android:padding="10dp">
<TextView
android:id="#+id/store_search_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="invisible" />
<TextView
android:id="#+id/store_search_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/store_search_category"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
C. Use adapter like this one and you can modify it based on your need
public class StoresSearchAdapter extends BaseAdapter {
// Declare Variables
Context mContext;
LayoutInflater inflater;
private List<Store> myList = null;
private ArrayList<Store> myArrayList;
public StoresSearchAdapter(Context context, List<Store> myList) {
mContext = context;
this.myList = myList;
inflater = LayoutInflater.from(mContext);
this.myArrayList = new ArrayList<Store>();
this.myArrayList.addAll(myList);
}
public class ViewHolder {
TextView store_search_id;
TextView store_search_name;
TextView store_search_category;
}
#Override
public int getCount() {
return myList.size();
}
#Override
public Store getItem(int position) {
return myList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(final int position, View view, ViewGroup parent) {
final ViewHolder holder;
if (view == null) {
holder = new ViewHolder();
view = inflater.inflate(R.layout.activity_stores_search_item, null);
// Locate the TextViews in activity_stores_search_item.xml
holder.store_search_id = (TextView) view.findViewById(R.id.store_search_id);
holder.store_search_name = (TextView) view.findViewById(R.id.store_search_name);
holder.store_search_category = (TextView) view.findViewById(R.id.store_search_category);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
// Set the results into TextViews
holder.store_search_id.setText(myList.get(position).getStr_id()+"");
holder.store_search_name.setText(myList.get(position).getStr_name());
String s = SplashActivity.db.getNameById(myList.get(position).getStr_cat_id()+"",SplashActivity.db.TABLE_CATEGORY,SplashActivity.db.COLUMN_CAT_NAME,SplashActivity.db.COLUMN_CAT_ID);
s = " in ("+ s + ")";
holder.store_search_category.setText(s);
return view;
}
// Filter Class
public void filter(String s) {
s = s.toLowerCase(Locale.getDefault());
myList.clear();
if (s.length() == 0) {
myList.addAll(myArrayList);
} else {
myList.addAll(SplashActivity.db.getAllStoresFiltered(s));
}
notifyDataSetChanged();
}
}
Finally your final output will be something like this one:
screenshot
This is my recyclerbackgroundtask
public class RecycleBackgroundTask extends AsyncTask{
Context ctx;
Activity activity;
RecyclerView recyclerView;
RecyclerView.Adapter adapter;
RecyclerView.LayoutManager layoutManager;
ArrayList<Post> arrayList = new ArrayList<>();
public RecycleBackgroundTask(Context ctx){
this.ctx = ctx;
activity = (Activity)ctx;
}
String json_string = "http://192.168.2.110/app/post.php";
#Override
public void onPreExecute() {
recyclerView = (RecyclerView)activity.findViewById(R.id.recyclerView);
layoutManager = new LinearLayoutManager(ctx);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(true);
adapter = new RecyclerAdapter(arrayList);
recyclerView.setAdapter(adapter);
}
#Override
public Void doInBackground(Void... params) {
try {
URL url = new URL(json_string);
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line=bufferedReader.readLine())!=null) {
stringBuilder.append(line+"\n");
}
httpURLConnection.disconnect();
String json_string = stringBuilder.toString().trim();
JSONObject jsonObject = new JSONObject(json_string);
JSONArray jsonArray = jsonObject.getJSONArray("server_response");
int count = 0;
while(count<jsonArray.length()){
JSONObject JO = jsonArray.getJSONObject(count);
count++;
Post post = new Post(JO.getString("headline"),JO.getString("source"),JO.getString("url"));
publishProgress(post);
}
Log.d("JSON STRING",json_string);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
public void onProgressUpdate(Post... values) {
arrayList.add(values[0]);
adapter.notifyDataSetChanged();
}
And my RecyclerAdapter
public class RecyclerAdapter extends RecyclerView.Adapter {
private static final int TYPE_HEAD = 0;
private static final int TYPE_LIST = 1;
ArrayList<Post> arrayList = new ArrayList<>();
public RecyclerAdapter (ArrayList<Post> arrayList){
this.arrayList = arrayList;
}
#Override
public RecyclerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if(viewType == TYPE_HEAD){
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_recycler,parent,false); // instead of row_recycler ,header_layout.
RecyclerViewHolder recyclerViewHolder = new RecyclerViewHolder(view,viewType);
return recyclerViewHolder;
}
if(viewType == TYPE_LIST){
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_recycler,parent,false);
RecyclerViewHolder recyclerViewHolder = new RecyclerViewHolder(view,viewType);
return recyclerViewHolder;
}
return null;
}
#Override
public void onBindViewHolder(RecyclerViewHolder holder, int position) {
if(holder.viewType == TYPE_LIST) {
Post post = arrayList.get(position-1);
holder.Headline.setText(post.getHeadline());
holder.Source.setText(post.getSource());
//holder.Url.setText(post.getUrl());
}
}
#Override
public int getItemCount() {
return arrayList.size()+1;
}
public static class RecyclerViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
TextView Headline,Source;//,Url;
int viewType;
public RecyclerViewHolder(View view,int viewType){
super(view);
if(viewType == TYPE_LIST) {
Headline = (TextView) view.findViewById(R.id.headline);
Source = (TextView) view.findViewById(R.id.source);
Headline.setOnClickListener(this);
Source.setOnClickListener(this);
// Url = (TextView) view.findViewById(R.id.url);
this.viewType = TYPE_LIST;
}else if (viewType == TYPE_HEAD){
this.viewType = TYPE_HEAD;
}
}
#Override
public void onClick(View v) {
Toast.makeText(v.getContext(), "ITEM PRESSED = " + String.valueOf(getAdapterPosition()), Toast.LENGTH_SHORT).show();
}
}
#Override
public int getItemViewType(int position){
if(position==0)
return TYPE_HEAD;
return TYPE_LIST;
}
public void setFilter(ArrayList<Post> newList){
arrayList = new ArrayList<>();
arrayList.addAll(newList);
notifyDataSetChanged();
}
}
Maybe that helps. i already set up a simple onclicklistener with a toast btw
Related
I have created an android application. in that application when I click on add, item added to the array list and this array list I want to show in Cart Activity. how to do that.
here is my activity1
public void addShirt(View view) {
MainActivity.cartItems.add(getString(R.string.shirt));
}
public void addPant(View view) {
MainActivity.cartItems.add(getString(R.string.pant));
}
public void view(View view) {
Intent i =new Intent(OnlyIron.this,CartActivity.class);
startActivity(i);
}
and cart activity is
for(int i=0; i<MainActivity.cartItems.size();i++) {
Toast.makeText(this, "item : " + MainActivity.cartItems.get(i), Toast.LENGTH_SHORT).show();
}
it showing toast but I enter code here want this show in listview
First lets Create model class and store data in it.
public class Cart {
private String id;
private String name;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Now to add items in that list i would call it this way :
private ArrayList<Cart > cart_array;
cart_array= new ArrayList<>();
Cart cart1 = new Cart ();
cart.setId("1");
cart.setName("first product");
Cart cart2 = new Cart ();
cart.setId("2");
cart.setName("first product");
Cart cart3 = new Cart ();
cart.setId("3");
cart.setName("first product");
//and than add your model into array
cart_array.add(cart1);
cart_array.add(cart2);
cart_array.add(cart3);
//and finaly set your adapter
Cart_Adapter adapter = new Cart_Adapter(cart_array, getActivity());
Recycler.setAdapter(adapter );
Please take a list view in CartActivity & create an Custom Adapter as according to your need(UI). Pass the MainActivity.cartItems this list to Adapter. It will start to show in your CartActivity.
You can see below example:
public class CustomAdapter extends BaseAdapter{
Activity mContext;
public ArrayList<String> mCartList = new ArrayList<String>();
private LayoutInflater mInflater=null;
public CustomAdapter(Activity activty, ArrayList<String> list)
{
this.mContext = activty;
mInflater = activty.getLayoutInflater();
this.mCartList=list;
}
#Override
public int getCount() {
if (mCartList != null){
return mCartList.size();
} else{
return 0;
}
}
#Override
public String getItem(int arg0) {
return mCartList.get(arg0);
}
#Override
public long getItemId(int index) {
return index;
}
#Override
public View getView(final int position, View convertView, ViewGroup arg2) {
final ViewHolder holder;
if (convertView == null ) {
holder = new ViewHolder();
convertView = mInflater.inflate(R.layout.item_layout, null);
holder.mItemNameTV= (TextView) convertView.findViewById(R.id.itemtv);
convertView.setTag(holder);
}
else {
holder = (ViewHolder) convertView.getTag();
}
holder.mNameTV.setText(mCartList.get(position));
return convertView;
}
private static class ViewHolder {
TextView mNameTV;
}
}
// Item Layout
<LinearLayout
android:layout_width="match_parent"
android:layout_height="#dimen/forty_dp"
android:gravity="center_horizontal"
android:orientation="vertical">
<TextView
android:id="#+id/fieldTV"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="#dimen/five_dp"
android:layout_weight="0.4"
android:padding="#dimen/ten_dp"
android:text="Custom Field"
android:textColor="#color/dark_gray_color"
android:textSize="#dimen/normal_font_size"
android:visibility="visible" />
</LinearLayout>
// Let Suppose your CartActivity is following:
ListView mListView = (ListView)findViewById(R.id.listview);
CustomAdapter adapter = new CustomAdapter(this, MainActivity.cartItems);
mListView.setAdapter(adapter);
I am working on listview example, I want tid from mysql database onclick selected listview .how to do it please help me , I am working from long time on that but can not found any solution.
ListTask Activity
public class ListTask extends Activity {
Task task_;
ListView listCollege;
ProgressBar proCollageList;
TextView GetTaskName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_task);
listCollege = (ListView)findViewById(R.id.tasklist);
proCollageList = (ProgressBar)findViewById(R.id.proCollageList);
GetTaskName = (TextView) findViewById(R.id.taskname);
new GetHttpResponse(this).execute();
}
private class GetHttpResponse extends AsyncTask<Void, Void, Void>
{
private Context context;
String result;
List<Task> Task_;
public GetHttpResponse(Context context)
{
this.context = context;
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0)
{
HttpService httpService = new HttpService("http://192.168.0.103/GroupBuilder/GetListTask.php");
try
{
httpService.ExecutePostRequest();
if(httpService.getResponseCode() == 200)
{
result = httpService.getResponse();
System.out.println("Result . . . "+result);
Log.d("Result", result);
if(result != null)
{
JSONArray jsonArray = null;
try {
jsonArray = new JSONArray(result);
JSONObject object;
JSONArray array;
// cources college;
Task_ = new ArrayList<Task>();
for(int i=0; i<jsonArray.length(); i++)
{
task_ = new Task();
object = jsonArray.getJSONObject(i);
task_.taskname = object.getString("taskname");
task_.tid = object.getString("tid");
System.out.println("Taask Tid "+task_.tid);
Task_.add(task_);
}
}
catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
else
{
Toast.makeText(context, httpService.getErrorMessage(), Toast.LENGTH_SHORT).show();
}
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
ListAdapter class
public class ListTaskAdapter extends BaseAdapter {
Context context;
List<Task> taskList;
Task task_;
public ListTaskAdapter(List<Task> listValue, Context context)
{
this.context = context;
this.taskList = listValue;
}
#Override
public int getCount() {
return this.taskList.size();
}
#Override
public Object getItem(int position) {
return this.taskList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, final ViewGroup viewGroup) {
ViewTaskName viewtaskname = null;
if(convertView == null)
{
viewtaskname = new ViewTaskName();
LayoutInflater layoutInfiater = (LayoutInflater)this.context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
//LayoutInflater layoutInfiater = LayoutInflater.from(context);
convertView = layoutInfiater.inflate(R.layout.listtaskadapter, null);
viewtaskname.task_name = (TextView)convertView.findViewById(R.id.taskname);
final String str = viewtaskname.task_name.getText().toString();
convertView.setTag(viewtaskname);
}
else
{
viewtaskname = (ViewTaskName) convertView.getTag();
}
viewtaskname.task_name.setText(taskList.get(position).taskname);
return convertView;
}
}
class ViewTaskName
{
TextView task_name;
}
class Task{
public String taskname;
public String tid;
}
activity_list_task.xml code
<ListView
android:id="#+id/tasklist"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:visibility="visible"
android:background="#38a2ed"
android:layout_marginTop="35dp" >
</ListView>
listadaper code
<TextView
android:id="#+id/taskname"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:text="TaskName"
android:textColor="#000000"
android:textSize="18sp"
/>
I am not getting any solution please help me and update my code , Thanks
You should use setOnItemClickListener
Register a callback to be invoked when an item in this AdapterView has
been clicked.
Create a TextView which hold ID like Name .
<TextView
android:id="#+id/taskID"
android:layout_width="0dp"
android:layout_height="0dp"
/>
Then
listCollege.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view,int position, long id)
{
TextView taskIDOBJ=(TextView)view.findViewById(R.id.taskID);
String item = tasknameOBJ.getText().toString();
Toast.makeText(this,"You selected : " + item,Toast.LENGTH_SHORT).show();
}
});
Simple way
String str_ID = Task_.get(position).tid;
Code
listCollege.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view,int position, long id)
{
String str_ID = Task_.get(position).tid;
Toast.makeText(this,"You selected : " + str_ID ,Toast.LENGTH_SHORT).show();
}
});
try this
//declare global use this array list in AsyncTask response to add
List<Tast> taskList = new ArrayList<>();
listCollege.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String tid = taskList.get(position).tid;
}
});
use setOnItemClickListener method and get id from sqllite , this method gives you a position , on the bases of position you got your id from bean class . follow this link .
Get Id from database in a listview onclick
view.setTag(id);
view.getTag();
I am new in Android. I am developing one app in android, Minimum API level is 15 and Maximum API level is 23.
I want like this, and another thing is multiple selection item in sub navigation. When any item is selected from parent navigation view, child navigation view will be open, as shown in image. I search on google but not getting answer. I see this and other so many stack overflow answer but not getting. please if some one help then it's very appreciate.Thanks in advance.
main_activity.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">
<ListView
android:id="#+id/lvList"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/colorPrimary"/>
</LinearLayout>
this is my javafile
public class HomePageActivity extends AppCompatActivity
{
ListView lvList;
ArrayList<String> arrayList;
NavigationViewAdapter adapter;
ArrayList<RowObject> selectedItemArray;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_hope_page);
lvList = (ListView)findViewById(R.id.lvList);
setUpListView();
lvList.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
lvList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
for (int i = 0; i < selectedItemArray.size(); i++)
{
if (i == position){
selectedItemArray.get(position).setSelectedItem(true);
}else{
selectedItemArray.get(i).setSelectedItem(false);
}
}
adapter.notifyDataSetChanged();
}
});
}
private void setUpListView()
{
arrayList = new ArrayList<>();
selectedItemArray = new ArrayList<>();
for (int i = 0; i < 20; i++)
{
arrayList.add("Item "+(i+1));
selectedItemArray.add(new RowObject(i, false));
}
adapter = new NavigationViewAdapter(HomePageActivity.this, arrayList, selectedItemArray);
if (adapter != null)
{
lvList.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
}
}
This is my adapter
public class NavigationViewAdapter extends BaseAdapter
{
Activity activity;
View itemView;
private LayoutInflater inflater;
private ViewHolder viewHolder;
ArrayList<String> arrayList;
ArrayList<RowObject> selectedItemArray;
public NavigationViewAdapter(Activity activity, ArrayList<String> arrayList, ArrayList<RowObject> selectedItemArray)
{
this.activity = activity;
this.arrayList = arrayList;
this.selectedItemArray = selectedItemArray;
inflater = (LayoutInflater)this.activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return arrayList.size();
}
#Override
public Object getItem(int position) {
return arrayList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent)
{
try
{
itemView = convertView;
if (convertView == null){
itemView = inflater.from(parent.getContext()).inflate(R.layout.main_activity_item, parent, false);
viewHolder = new ViewHolder();
//if this is first time then inflate view
viewHolder.itemName = (TextView)itemView.findViewById(R.id.itemName);
itemView.setTag(viewHolder);
}else{
viewHolder = (ViewHolder)itemView.getTag();
}
//set Data from ArrayList
viewHolder.itemName.setText(arrayList.get(position));
if (selectedItemArray.get(position).isSelectedItem()){
viewHolder.itemName.setBackgroundColor(activity.getResources().getColor(R.color.colorPrimaryDark));
}else{
viewHolder.itemName.setBackgroundColor(activity.getResources().getColor(R.color.colorPrimary));
}
notifyDataSetChanged();
return itemView;
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
public class ViewHolder
{
TextView itemName;
}
}
this is my RowObject.java
public class RowObject
{
public int position;
boolean isSelectedItem;
public RowObject(int position, boolean isSelectedItem) {
this.position = position;
this.isSelectedItem = isSelectedItem;
}
public int getPosition() {
return position;
}
public void setPosition(int position) {
this.position = position;
}
public boolean isSelectedItem() {
return isSelectedItem;
}
public void setSelectedItem(boolean isSelectedItem) {
this.isSelectedItem = isSelectedItem;
}
}
I think this type of layout is not provided by android but you can fixed using your logic. I think you need to change your xml file, because your listview width is match_parent so your whole screen filled and your second sub menu is not display.Please change that or fix as per your requirement. Your main xml file.
main_activity.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">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_vertical">
<ListView
android:id="#+id/lvList"
android:layout_width="100dp"
android:layout_height="match_parent"
android:background="#color/colorPrimary"/>
<ScrollView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/lvList"
android:layout_toEndOf="#+id/lvList">
<LinearLayout
android:id="#+id/llItemContainer"
android:layout_width="200dp"
android:layout_height="50dp"
android:orientation="vertical"
android:background="#color/input_login_hint">
</LinearLayout>
</ScrollView>
</RelativeLayout>
</LinearLayout>
And add one method in your listview onItemClickListener(). Please see my code.
java file.
public class NavigationActivity extends AppCompatActivity
{
ListView lvList;
LinearLayout llItemContainer;
ArrayList<String> arrayList;
NavigationViewAdapter adapter;
ArrayList<RowObject> selectedItemArray;
ArrayList<String> selectedSecondItem;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.navigation_activity);
lvList = (ListView)findViewById(R.id.lvList);
setUpListView();
lvList.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
llItemContainer = (LinearLayout)findViewById(R.id.llItemContainer);
lvList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
for (int i = 0; i < selectedItemArray.size(); i++)
{
if (i == position){
selectedItemArray.get(position).setSelectedItem(true);
}else{
selectedItemArray.get(i).setSelectedItem(false);
}
}
adapter.notifyDataSetChanged();
//here you can pass your sub view item array
generateSubView(position);
}
});
}
private void setUpListView()
{
arrayList = new ArrayList<>();
selectedItemArray = new ArrayList<>();
for (int i = 0; i < 20; i++)
{
arrayList.add("Item "+(i+1));
selectedItemArray.add(new RowObject(i, false));
}
adapter = new NavigationViewAdapter(NavigationActivity.this, arrayList, selectedItemArray);
if (adapter != null)
{
lvList.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
}
private void generateSubView(int position)
{
try
{
selectedSecondItem = new ArrayList<>();
llItemContainer.removeAllViews();
for (int i = 0; i <= position; i++)
{
final TextView rowText = new TextView(NavigationActivity.this);
TableRow.LayoutParams paramsExample = new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT,
147,2.0f);
rowText.setId(i);
rowText.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
rowText.setGravity(Gravity.CENTER_VERTICAL);
rowText.setTextColor(getResources().getColor(android.R.color.white));
paramsExample.setMargins(3, 3, 3, 3);
rowText.setPadding(25, 25, 25, 25);
rowText.setTextSize(18);
rowText.setText("SecondItem " + i);
rowText.setLayoutParams(paramsExample);
rowText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
rowText.setBackgroundColor(getResources().getColor(R.color.colorAccent));
selectedSecondItem.add(rowText.getText().toString());
}
});
llItemContainer.addView(rowText);
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
you get the selected item from sub navigation view in selectedSecondItem arraylist.
Android Studio > New > Activity > Master/Detail Flow
Google docs link
OR
Stackoverflow answer
I'm new in android and stuck at one step, so really need someones help.
I m code for small piece of program, that should parse Json local file, and post it to activity. Image decode with Base64 to Bitmap and given to CustomAdapter(extends Base Adapter). I check program's steps with Log.
AsyncTask make all correct, but in method "Oncreate view" it seems to run nothing.
Her is my code. I m really have no idea , what the problem, help!
My MainFragment+AsyncTask
public class MainFragment extends Fragment {
ArrayList<Bitmap> bitArray;
public MainFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
ListView listview = (ListView)rootView.findViewById(R.id.listViewPost);
Log.v("Pl","1");
listview.setAdapter(new CustomListAdapter(getContext(), bitArray));
listview.setOnItemClickListener(new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
Toast.makeText(getActivity(), "YESS", Toast.LENGTH_SHORT).show();
}
});
return rootView;
}
#Override
public void onStart() {
super.onStart();
}
private void updatePost() {
FetchPosterTask postTask = new FetchPosterTask(getActivity());
postTask.execute("uk_news.json");
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
updatePost();
}
class FetchPosterTask extends AsyncTask<String, Void, ArrayList<Bitmap>> {
private final String LOG_TAG = FetchPosterTask.class.getSimpleName();
private Context context;
public FetchPosterTask (Context myContext) {
this.context = myContext;
}
#Override
protected ArrayList<Bitmap> doInBackground(String... params) {
if(params.length ==0 ){
return null;
}
String json = null;
try {
json = getJson(params[0]);
} catch (IOException e)
{
e.printStackTrace();
}
try {
String[] masPst = getPosterfromJsonAsString(json);
ArrayList<Bitmap> result =decodeImageToBitmap(masPst);
return result;
}catch (JSONException e){
Log.e(LOG_TAG, "Place 5", e);
}
return null;
}
private String getJson(String filename) throws IOException{
InputStream is = this.context.getAssets().open(filename);
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
return new String(buffer);
}
private String[] getPosterfromJsonAsString(String posterJson) throws JSONException {
final String OWM_NFO = "nfo";
final String OWM_NWS = "nws";
final String OWM_PST = "pst";
JSONObject imageJson = new JSONObject(posterJson);
JSONObject nfoArray = imageJson.getJSONObject(OWM_NFO);
JSONArray nwsArray = nfoArray.getJSONArray(OWM_NWS);
String[] resultStr = new String[nwsArray.length()];
for(int i =0; i<nwsArray.length(); i++){
JSONObject pst = nwsArray.getJSONObject(i);
String im = pst.getString(OWM_PST);
resultStr[i] = im;
}
return resultStr;
}
public ArrayList<Bitmap> decodeImageToBitmap (String[] base64Image) {
ArrayList<Bitmap> bitmapArrayList = new ArrayList<Bitmap>();
for(int i =0; i<4; i++) {
byte[] decodedString = Base64.decode(base64Image[i], Base64.DEFAULT);
Bitmap base64Bitmap = BitmapFactory.decodeByteArray(decodedString, 0,
decodedString.length);
bitmapArrayList.add(i, base64Bitmap);
}
return bitmapArrayList;
}
#Override
protected void onPostExecute(ArrayList<Bitmap> bitmapArrayList) {
if(bitArray == null){
bitArray = new ArrayList<>(bitmapArrayList);
}
else{
for(Bitmap bit: bitmapArrayList){
bitArray.clear();
bitArray.add(bit);
}
}
}
}
}
CustomListAdapter
public class CustomListAdapter extends BaseAdapter {
private final String LOG_TAG = CustomListAdapter.class.getSimpleName();
private ArrayList<Bitmap> bitmapArrayList;
private LayoutInflater layoutInflater;
public CustomListAdapter(Context context, ArrayList<Bitmap> bitmapArrayList) {
this.bitmapArrayList = bitmapArrayList;
this.layoutInflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return 0;
}
#Override
public Object getItem(int position) {
return bitmapArrayList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if(convertView == null) {
convertView = layoutInflater.inflate(R.layout.list_post_item, null);
holder = new ViewHolder();
holder.imageView = (ImageView) convertView.findViewById(R.id.list_item);
convertView.setTag(holder);
Log.v(LOG_TAG,"1");
}
else {
holder = (ViewHolder) convertView.getTag();
Log.v(LOG_TAG,"2");
}
Log.v(LOG_TAG,"3");
holder.imageView.setImageBitmap((Bitmap)getItem(position));
Log.v(LOG_TAG,"4");
return convertView;
}
static class ViewHolder {
ImageView imageView;
}
}
Layouts
list_post_item
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/list_item"/>
</LinearLayout>
fragment main
<?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">
<ListView
android:layout_width="273dp"
android:layout_height="wrap_content"
android:id="#+id/listViewPost" />
</LinearLayout>
Your Adapter Has Not Any Item So Please change That on Adapter
#Override
public int getCount() {
return bitmapArrayList.size();
}
And also call updatePost() methed in onActivityCreated() Mehhed
EmptyView in ListView appears on page even though the list is not empty.
(I'm not using ListActivity)
Even when I remove the setEmptyView(...) it makes no change!
What am I supposed to do?
Here is the code to my List Fragment:
public class SearchResultListFragment extends Fragment{
Pagination pagination;
boolean loadingMore = false;
ListView list;
TextView text1;
TextView text2;
TextView text3;
TextView text4;
TextView text5;
Button Btngetdata;
private static String url = "https://www.....com/api/property/search";
private static int currentFirstVisibleItem;
public SearchResultArrayListAdaptor adapter ;
LinearLayout linlaHeaderProgress;
JSONArray jsonArray = null;
JSONParse fetchclass = null;
public SearchResultListFragment() {
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
linlaHeaderProgress = (LinearLayout) getActivity().findViewById(R.id.linlaHeaderProgress);
ArrayAdapter<PropertyObject> aa =(ArrayAdapter<PropertyObject>) list.getAdapter();
if (aa!= null){
aa.clear();
aa.notifyDataSetChanged();
}
list.setOnItemClickListener((OnItemClickListener) getActivity());
adapter = new SearchResultArrayListAdaptor(getActivity(), R.layout.list_view_items, new ArrayList<PropertyObject>());
list.setAdapter(adapter);
pagination = new Pagination(0,15);
fetchclass = new JSONParse(getActivity());
fetchclass.execute(url);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_search_result_list, container, false);
list=(ListView)rootView.findViewById(R.id.listViewSearchResult);
list.setOnScrollListener(
new OnScrollListener(){
private int currentVisibleItemCount;
private int currentTotalItemCount;
private int currentScrollState;
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
this.currentScrollState = scrollState;
this.isScrollCompleted();
}
private void isScrollCompleted() {
if (currentFirstVisibleItem + currentVisibleItemCount >= currentTotalItemCount) {
if (this.currentVisibleItemCount > 0 && this.currentScrollState == SCROLL_STATE_IDLE) {
if(fetchclass!=null) {
pagination = new Pagination(this.currentTotalItemCount,15);
if(!(fetchclass.getStatus()== AsyncTask.Status.RUNNING)) {
fetchclass= new JSONParse(getActivity());
fetchclass.execute(url);
}
}
else {
fetchclass = new JSONParse(getActivity());
fetchclass.execute(url);
}
}
}
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
currentFirstVisibleItem = firstVisibleItem;
this.currentVisibleItemCount = visibleItemCount;
this.currentTotalItemCount = totalItemCount;
}
});
return rootView;
}
//*********************************** inner class
public class JSONParse extends AsyncTask<String, String, JSONObject> {
Context mContext;
int checkBoxRooms;
public JSONParse(Context context){
mContext = context;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
linlaHeaderProgress.setVisibility(View.VISIBLE);
}
#Override
protected JSONObject doInBackground(String... args) {
JSONObject json = null;
PropertyFilter searchFilter = SearchFilterManager.initializePropertyFilter(new PropertyFilter(), getArguments());
getActivity().setProgressBarIndeterminateVisibility(true);
JSONParserForSearch jParser = new JSONParserForSearch();
json = jParser.getJSONFromUrl(url, searchFilter, pagination);
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
// SHOW THE SPINNER WHILE LOADING FEEDS
getActivity().setProgressBarIndeterminateVisibility(false);
PropertyObject propertyObject;
try {
jsonArray = json.getJSONArray("PropertyListings");
if (jsonArray == null || jsonArray.length()<1){
// list.setEmptyView(getActivity().findViewById(R.id.txtNoResult));
}
else {
for(int i = 0; i < jsonArray.length(); i++){
JSONObject c = jsonArray.getJSONObject(i);
propertyObject = new Gson().fromJson(c.toString(), new PropertyObject().getClass());
adapter.add(propertyObject);
adapter.notifyDataSetChanged();
}
}
// CHANGE THE LOADINGMORE STATUS TO PERMIT FETCHING MORE DATA
loadingMore = false;
// HIDE THE SPINNER AFTER LOADING FEEDS
linlaHeaderProgress.setVisibility(View.GONE);
}
catch (JSONException e) {
e.printStackTrace();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
}
My layout XML:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_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"
android:orientation="vertical"
tools:context="com.khoonat.khoonat2.SearchResultListActivity$SearchResultListFragment">
<ListView
android:id="#+id/listViewSearchResult"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:layout_weight="2"
>
</ListView>
<LinearLayout
android:id="#+id/linlaHeaderProgress"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="vertical"
android:visibility="gone"
>
My Adapter is ArrayAdapter.
I have implemented isEmpty and getCount too.
Here is my Adapter:
public class SearchResultArrayListAdaptor extends ArrayAdapter<PropertyObject>{
Context context;
int layoutResourceId; // This is the layout you created for the list items
ArrayList<PropertyObject> items;
public SearchResultArrayListAdaptor(Context context, int layoutResourceId, ArrayList<PropertyObject> items) {
super(context, layoutResourceId, items);
this.items = items;
this.layoutResourceId = layoutResourceId;
this.context = context;
}
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
LayoutInflater inflater = ((Activity) getContext()).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
TextView txtLarge1 =
(TextView)row.findViewById(R.id.listViewSearchResultTxtLarge1);
TextView txtLarge2 =
(TextView)row.findViewById(R.id.listViewSearchResultTxtLarge2);
#Override
public int getCount() {
if (items == null)
return 0;
else
return items.size();
}
#Override
public boolean isEmpty(){
if (items == null || items.size()==0)
return true;
return false;
}
My Activity For List:
public class SearchResultListActivity extends ActionBarActivity implements OnItemClickListener{
static PropertyObject selectedPropertyObject;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
Bundle bundle=new Bundle();
bundle.putInt("intentionOfOwner", intent.getIntExtra("intentionOfOwner",0));
SearchResultListFragment fragobj=new SearchResultListFragment();
fragobj.setArguments(bundle);
///back button
setContentView(R.layout.activity_search_result_list);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction().add(R.id.container, fragobj).commit();
}
}
#Override
public void onItemClick(AdapterView<?> arg0, View textView, int rowNumber, long arg3) {
Intent intent = new Intent(this, PropertyDetailActivity.class);
PropertyObject po = (PropertyObject) arg0.getAdapter().getItem((int)arg3);
intent.putExtra("listingID",po.getID());
startActivity(intent);
}
any guess?
thanks a lot in advance.
I think the problem is around here, not applicable if you are doing lazy list loading
for(int i = 0; i < jsonArray.length(); i++){
JSONObject c = jsonArray.getJSONObject(i);
propertyObject = new Gson().fromJson(c.toString(), new PropertyObject().getClass());
adapter.add(propertyObject);
adapter.notifyDataSetChanged();
}
try like
ArrayList<PropertyObject> items = new ArrayList<PropertyObject>();
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject c = jsonArray.getJSONObject(i);
propertyObject = new Gson().fromJson(c.toString(), new PropertyObject().getClass());
items.add(propertyObject);
}
adapter.items = items;
adapter.notifyDataSetChanged();