How to create when i click 1st item in arrayList1 will open page with 1st item in arrayList2 - android-studio

When I click first or second item from 1st array list I get first item from array list two, but I need if i click second item on array list 1 I get shown second item from list two
public class SecondActivity extends AppCompatActivity {
ListView listView;
ArrayList<String> 1stArrayList;
ArrayList<String> 2ndArrayList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second_activity);
listView = (ListView) findViewById(R.id.listView);
1stArrayList = new ArrayList<>();
1stArrayList .add("A");
1stArrayList .add("B");
1stArrayList .add("C");
2ndArrayList = new ArrayList<>();
2ndArrayList.add("1");
2ndArrayList.add("2");
2ndArrayList.add("3");
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, R.layout.item, 1stArrayList);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
String 2ndArrayList= listView.getItemAtPosition(position).toString();
SharedPreferences settings = getSharedPreferences("PREFS", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("2ndArrayList ", 2ndArrayList );
editor.apply();
Intent intent = new Intent(getApplicationContext(), ThirdActivity.class);
startActivity(intent);
}
});
}
}

A possible solution would be getting the value directly from the array using the position of the view clicked. Like the following:
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
String secListItem = secArrayList.get(position);
SharedPreferences settings = getSharedPreferences("PREFS", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("2ndArrayList", secListItem );
editor.apply();
Intent intent = new Intent(getApplicationContext(), ThirdActivity.class);
startActivity(intent);
}
});
But you have to be sure that both the arrays will have the same size or you may have an IndexOutOfBoundsException.
Another solution would be using some Map with the values from arraylist1 and arraylist2, implementing a custom adapter that extends BaseAdapter, populating the views with the values from the first array with getView() and using getItem() to return the values from the second list, but that's harder to do.
Also if you don't mean to persist the item and only transfer them between activities, you can use the Intent to do it. In this way:
Intent intent = new Intent(getApplicationContext(), ThirdActivity.class);
Intent.putExtra("2ndArrayList", secListItem);
startActivity(intent);
And recover in the third activity with something like:
String secArrayItem = "";
Bundle extras = getIntent().getExtras();
if (extras != null) secArrayItem = extras.getString("2ndArrayList");

Related

Searchview should filter only first 5 characters from a listview androidstudio

When i search it should only search first five characters from the array,
this is an app for finding dreams meaning, its like a dictionary app.
I added 2 listviews, and using a searchview to filter the results. but when i use searchview its searching the whole content in the array, and listing the result based on it which cause wrong results.
if i could search only the first five characters from these arrays, it will help me to get right results.
this is how i get the data from database
listView2 = findViewById(R.id.listView2);
sr_txt = findViewById(R.id.sr_txt);
listView = findViewById(R.id.listView);
databaseReference = FirebaseDatabase.getInstance().getReference("dreamapp");
dream1 = new Dream();
title_list = new ArrayList<>();
answer_list = new ArrayList<>();
arrayAdapter = new ArrayAdapter<>(this, R.layout.item, R.id.item, title_list);
arrayAdapter2 = new ArrayAdapter<>(this, R.layout.item2, R.id.item2, answer_list);
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot d : snapshot.getChildren()) {
dream1 = d.getValue(Dream.class);
title_list.add(dream1.getTitle());
answer_list.add(dream1.getAnswer());
}
listView.setAdapter(arrayAdapter);
listView2.setAdapter(arrayAdapter2);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int i, long id) {
Intent intent = new Intent(MainActivity.this, answer.class);
// String q = answer_list.get(i);
// String p =answer_list.get(i);
String q = (String) arrayAdapter2.getItem(i);
intent.putExtra("answer", q);
startActivity(intent);
}
});
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
this is my searchview.
sr_txt.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
MainActivity.this.arrayAdapter.getFilter().filter(query);
MainActivity.this.arrayAdapter2.getFilter().filter(query);
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
MainActivity.this.arrayAdapter.getFilter().filter(newText);
MainActivity.this.arrayAdapter2.getFilter().filter(newText);
return false;
}
});
Please give more detail of what you want.It would be more clear if you dont mind uploading image of what you are getting and what you want.

Get recycler view items in spinner in another activity

I use retrofit2 to get a category list with a model class and recyclerview adapter to get category items. In another activity I have a spinner to show category items.
How can I get category items in another activity and show in spinner?
Here is my code:
public class CatAdapter extends RecyclerView.Adapter<CatAdapter.MyViewHolder> {
private Context context;
private List<Category> cats;
public CatAdapter(Context context, List<Category> cats) {
this.context = context;
this.cats = cats;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.cats_list, parent, false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(MyViewHolder holder, final int position) {
holder.cat_title.setText(cats.get(position).getTitle());
holder.cat_content.setText(cats.get(position).getContent());
holder.cat_qcount.setText(cats.get(position).getQcount());
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context , CatPosts.class);
intent.putExtra("catid",cats.get(position).getCatid());
intent.putExtra("cattitle",cats.get(position).getTitle());
context.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return cats.size();
}
class MyViewHolder extends RecyclerView.ViewHolder {
private TextView cat_title,cat_content, cat_qcount;
public MyViewHolder(View itemView) {
super(itemView);
cat_title = itemView.findViewById(R.id.cat_title);
cat_content = itemView.findViewById(R.id.cat_content);
cat_qcount = itemView.findViewById(R.id.cat_qcount);
}
}
}
I don't want to get items with intent because there is no click action when need to cat items.
I have an activity for sending new posts. In this activity there is a spinner that shows cat items and user select a category.
The intent in adapter sends data to CatPosts when an item is clicked. I want to get cat list when the new Post activity is shown.
You were doing fine, now in the other activity, on your onCreate() method, do this:
Intent intent = getIntent();
catId = intent.getStringExtra("catid");
catTitle = intent.getStringExtra("cattitle");
String[] x = new String[]{catId,catTitle};
ArrayAdapter<String> adapterX = new ArrayAdapter<>(this, android.R.layout.your_spinner_in_xml, x);
spinner.setAdapter(adapterX);
If i get question you want access to List in two activity.
If so then you have several way
1 : Store To local Database or SharedPreferences
2 : use static variables(easy way)
When you get list of category from retrofit response, store it to static List like below
public static List<Category> cats;
Then in OnResponse()
cats = response.body().getCats();
Now you access cats in anOther activtiy.

Creating a very custom list

I'm developping an application, and now, I don't know what to do next:
I have a list of elements, each element has some informations + an ID + a logo.
What I want to do is creating a list like in the picture
List
Of course, I want it in a single layer, with the logo, some informations, and a button to define an action; where I could use the ID of the selected item.
I did some research, may be I found some relative subjects, but none of what I want.
My list is a
ArrayList<ArrayList<String>>
filled by data from database.
Thank you
Here it is:
public class Avancee extends Activity {
// Log tag
private static final String TAG = MainActivity2.class.getSimpleName();
// Movies json url
private static final String url = "http://blabla.com/movie.json";
private ProgressDialog pDialog;
private List<Movie> movieList = new ArrayList<Movie>();
private ListView listView;
private CustomListAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.list);
adapter = new CustomListAdapter(this, movieList);
listView.setAdapter(adapter);
pDialog = new ProgressDialog(this);
// Showing progress dialog before making http request
pDialog.setMessage("Loading...");
pDialog.show();
// changing action bar color
getActionBar().setBackgroundDrawable(
new ColorDrawable(Color.parseColor("#1b1b1b")));
// Creating volley request obj
JsonArrayRequest movieReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
//Log.d(TAG, response.toString());
hidePDialog();
String result = getIntent().getStringExtra("ITEM_EXTRAA");
System.out.println(result);
try{
JSONArray ja = new JSONArray(result);
for (int i = 0; i < ja.length(); i++) {
try {
JSONObject obj = ja.getJSONObject(i);
Movie movie = new Movie();
movie.setTitle(obj.getString("title"));
movie.setLocation(obj.getString("location_search_text"));
movie.setId(obj.getInt("id"));
// adding movie to movies array
movieList.add(movie);
} catch (JSONException e) {
e.printStackTrace();
}
}
}catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(movieReq);
}
#Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
It's the "id" that I want to get in the OnClick event.
use this code
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
Movie movie= movieList.get(position);
}
});
//here position will give you the id of listview cell so you can use it like
Movie movie= movieList.get(position);
then you can use it get all the data inside your moview object

dynamically adding textviews to listview item

I have this arryalist of items, each item has hour as string and string of minutes. I can split minutes to array and for each minute I want to add textview with on clicklistener.
I have implemented arrayadapter for listview. Everything works like expected but only one thing : I don't see all textviews as they are not shown properly on the end of the display.
ListView row item layout has LinearLayout and textview to show hours.
Code for listview adapter :
public class DotazAdapter extends ArrayAdapter<Hours> {
private final ArrayList<Hours> model;
private final Context context;
public DotazAdapter(Context context, ArrayList<Hours> model) {
super(context, R.layout.hours_minutes,model);
this.model=model;
this.context=context;
// TODO Auto-generated constructor stub
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row = null;
row = inflater.inflate(R.layout.hours_minutes, parent,false);
LinearLayout riadok = (LinearLayout)row.findViewById(R.id.horny);
TextView hodiny = (TextView)row.findViewById(R.id.hodinyBTV);
hodiny.setText(model.get(position).getHour());
String[] minuty = model.get(position).getMinutes().split(" ");
for(int i = 0; i<minuty.length;i++){
final TextView minutka = new TextView(context);
minutka.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
minutka.setText(minuty[i]+" ");
minutka.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, "Stlacil si riadok "+position+ " a cislo v riadku :", Toast.LENGTH_SHORT).show();
}
});
riadok.addView(minutka, );
}
return row;
}
}
Layout for listitem :
xml version=1.0 encoding=utf-8
LinearLayout xmlnsandroid=httpschemas.android.comapkresandroid
androidid=#+idhorny
androidlayout_width=match_parent
androidlayout_height=wrap_content
TextView
androidid=#+idhodinyBTV
androidlayout_width=wrap_content
androidlayout_height=wrap_content
androidlayout_marginRight=5dp
androidbackground=#F00C0C
androidtextColor=#FFFFFF
androidtextSize=18sp
LinearLayout

SherlockFragmentActivity with SherlockListFragment

I have 3 tabs and all of them has lists inside(different ones of course). When i click on tab I see the proper result(result which i would like to get).
I know how to get the clicked item info and make request to database about that item and get result and create new intent and put that result in it as a extra. BUT i don't know how I can display my result inside the same fragment without creating new intent. Because when i create new intent and show result in new intent my tabs obviously disappears, but i need them always to be there.
My main activity:
public class MainActivity extends SherlockFragmentActivity
{
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
actionBar.setDisplayShowTitleEnabled(true);
Tab tab = actionBar.newTab()
.setText("Dictionary")
.setTabListener(new DictionaryFragment())
.setIcon(R.drawable.android);
actionBar.addTab(tab);
tab = actionBar.newTab()
.setText("Play")
.setTabListener(new PlayFragment())
.setIcon(R.drawable.apple);
actionBar.addTab(tab);
tab = actionBar.newTab()
.setText("Manage")
.setTabListener(new ManageFragment())
.setIcon(R.drawable.apple);
actionBar.addTab(tab);
}
}
One of my fragments:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
built_in_DB_setup dbOpenHelper = new built_in_DB_setup(getActivity().getBaseContext(), DB_NAME);
database = dbOpenHelper.openDataBase();
fillFreinds();
ArrayAdapter<String> adapter = new
ArrayAdapter<String>(getActivity().getBaseContext(), android.R.layout.simple_expandable_list_item_1, friends);
setListAdapter(adapter);
return super.onCreateView(inflater, container, savedInstanceState);
}
And here is the item click listener inside this class
public void onListItemClick(ListView l, View v, int position, long id)
{
super.onListItemClick(l, v, position, id);
String a=getData(((TextView) v).getText().toString());
Intent i = new Intent("com.example.fragmenttest.VIEWWORD");
i.putExtra("result", a);
startActivity(i);
}
Ones I have String a which i have got from onListItemClick how can I replace current Tab data with this string?

Resources