How to get a integer value about Arraylist index - java

How to get a integer value for arraylist item index ,if you click arraylist fifth number then the integer value a=5
How can i do this?
ArrayList a;
al = new ArrayList();
for(int i = 0; i < linksArray.length(); ++i) {
a.add(linksArray.getJSONObject(i).get("fullText"));
}
I added my json values in "a"
adapter = new ArrayAdapter(this,R.layout.activity_listview_2, a);
listviewMakale.setAdapter(adapter);
and then I have listview click function and i want to if click fifth element
int indexItem = 5; I don't want to with listview click listener position value, I want to arraylist index.
all activity code,the main problem is if users search anything in edittext
ListView listviewMakale;
ArrayList a22 = new ArrayList();
ArrayList al;
private ArrayAdapter adapter;
private EditText ara;
String url = "myurl";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.makale);
ActionBar actionBar = getSupportActionBar();
actionBar.setIcon(R.mipmap.ic_launcher);
actionBar.setDisplayShowHomeEnabled(true);
listviewMakale = (ListView)findViewById(R.id.listviewMakale);
StringRequest request = new StringRequest(url, new Response.Listener<String>() {
#Override
public void onResponse(String string) {
parseJsonData(string);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
Toast.makeText(getApplicationContext(), "Hata-Tekrar Deneyiniz!!", Toast.LENGTH_SHORT).show();
}
});
StringRequest request2 = new StringRequest(url, new Response.Listener<String>() {
#Override
public void onResponse(String string) {
parseJsonDataLinks(string);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
Toast.makeText(getApplicationContext(), "Hata-Tekrar Deneyiniz!!", Toast.LENGTH_SHORT).show();
}
});
//baslık için
RequestQueue rQueue = Volley.newRequestQueue(makale.this);
rQueue.add(request);
//linkler için
RequestQueue rQueue2 = Volley.newRequestQueue(makale.this);
rQueue2.add(request2);
}
void parseJsonData(String jsonString) {
try {
JSONObject object = new JSONObject(jsonString);
JSONArray linksArray = object.getJSONArray("makale");
al = new ArrayList();
for(int i = 0; i < linksArray.length(); ++i) {
al.add(linksArray.getJSONObject(i).get("fullText"));
}
adapter = new ArrayAdapter(this,R.layout.activity_listview_2, al);
listviewMakale.setAdapter(adapter);
EditText ara=(EditText) findViewById(R.id.ara);
listviewMakale.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
final String linkler="url"+a22.get(position);
Toast.makeText(makale.this,String.valueOf(al.indexOf(position)),Toast.LENGTH_SHORT).show();
AlertDialog.Builder builder = new AlertDialog.Builder(makale.this);
builder.setTitle("Makale");
builder.setMessage("");
builder.setNegativeButton("İPTAL", new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int id) {
}
});
builder.setPositiveButton("TAMAM", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse(linkler), "text/html");
startActivity(intent);
}
});
builder.show();
}
});
ara.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
makale.this.adapter.getFilter().filter(charSequence);
}
#Override
public void afterTextChanged(Editable editable) {
}
});
} catch (JSONException e) {
e.printStackTrace();
}
}
//linklere erişiyoruz
void parseJsonDataLinks (String jsonString2) {
try {
JSONObject object2 = new JSONObject(jsonString2);
JSONArray linksArray2 = object2.getJSONArray("makale");
for(int j = 0; j < linksArray2.length(); ++j) {
a22.add(linksArray2.getJSONObject(j).get("link"));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}

you can get item you want from directly adapter like this:
adapter.getItem(position)
position is index of item.

You can get clicked position on ListView OnItemClickListener. And that position will be your ArrayList position. You can easily retrieve value for that position from ArrayList.
your_list_view.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int pos, long l) {
String full_text = adapterView.getAdapter().getItem(pos);
Log.w("Clicked Row", "Data on position " + pos + " is " + full_text);
}
});
You can also use
String full_text = your_array_list.get(pos); in place of String full_text = adapterView.getAdapter().getItem(pos);. Both will return you same value.

Once you will bind the ArrayList with ListView then it will not change their position until you refresh or reload it.
So you can get values from ArrayList by its clicked position of ListView.
You can do like.
arrayList.get(index);
It will return object whatever you passed.

Related

Pasting text into a multiautocompletetextview with an auto select function into a chip

I am trying to get the text from my ocr scanner result to the next activity into a multiautocompletetextview that will auto select the options and enter a chip so it can be searched.
So far I haven't found any solutions to this problem. I am a beginner.
public class SearchIngredientActivity extends AppCompatActivity implements RecyclerItemSelectedListener,View.OnClickListener {
Toolbar toolbar;
ChipGroup chipGroup;
Button searchBtn;
Context context;
SwipeRefreshLayout swipeRefreshLayout;
List<Recipe> recipeList = new ArrayList<>();
List<String> ingredientList = new ArrayList<>();
List<String> chipList = new ArrayList<>();
ArrayAdapter<String> arrayAdapter;
String search, selected, string;
RecyclerView rv;
MultiAutoCompleteTextView inputEditText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search_by_ingredients);
toolbar = findViewById(R.id.toolbar_search);
setSupportActionBar(toolbar);
chipGroup = findViewById(R.id.chip_group);
searchBtn = findViewById(R.id.ingredient_search_btn);
inputEditText = findViewById(R.id.text_input_et);
swipeRefreshLayout = findViewById(R.id.swipe_refresh);
rv = findViewById(R.id.recycler_search_results);
rv.setLayoutManager(new LinearLayoutManager(context));
string = inputEditText.getText().toString();
String receivingdata = getIntent().getStringExtra("Text");
MultiAutoCompleteTextView mtv = (MultiAutoCompleteTextView)findViewById(R.id.text_input_et);
mtv.setText(receivingdata);
inputEditText.setOnItemClickListener((adapterView, view1, i, l) -> {
selected = (String) adapterView.getItemAtPosition(i);
SearchIngredientActivity.this.onItemSelected(selected);
inputEditText.setText("");
chipList.add(selected);
});
inputEditText.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) {
string = s.toString();
if (!string.equals("")) {
getSearchSuggestions(string);
} else
Toast.makeText(getApplicationContext(), "Select something...", Toast.LENGTH_LONG).show();
}
#Override
public void afterTextChanged(Editable editable) {
}
});
searchBtn.setOnClickListener(v -> {
InputMethodManager in = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
in.hideSoftInputFromWindow(inputEditText.getWindowToken(),0);
search = getSelectedChips(chipGroup);
getRecipesByIngredients(search);
});
if (savedInstanceState != null) {
string = savedInstanceState.getString("name");
search = savedInstanceState.getString("results");
inputEditText.setText("");
getSearchSuggestions(string);
getRecipesByIngredients(search);
chipList = savedInstanceState.getStringArrayList("chip");
for (int i = 0; i < chipList.size(); i++) {
String s = chipList.get(i);
onItemSelected(s);
}
}
}
#Override
public void onSaveInstanceState(#NonNull Bundle outState) {
outState.putString("name", string);
outState.putString("results", search);
outState.putStringArrayList("chip", (ArrayList<String>) chipList);
super.onSaveInstanceState(outState);
}
public void getSearchSuggestions(String query) {
RecipeApi recipeApi = RetrofitClient.getRecipeApi();
Call<List<Ingredient>> call = recipeApi.ingredientList(query);
call.enqueue(new Callback<List<Ingredient>>() {
#Override
public void onResponse(#NotNull Call<List<Ingredient>> call, #NotNull Response<List<Ingredient>> response) {
List<Ingredient> names = response.body();
ingredientList.clear();
for (int i = 0; i < Objects.requireNonNull(names).size(); i++) {
ingredientList.add(names.get(i).getLocalizedName());
}
arrayAdapter = new ArrayAdapter<>(getApplicationContext(), android.R.layout.simple_dropdown_item_1line, ingredientList);
inputEditText.setAdapter(arrayAdapter);
inputEditText.setTokenizer(new MultiAutoCompleteTextView.CommaTokenizer());
//inputEditText.setThreshold(1);
}
#Override
public void onFailure(#NotNull Call<List<Ingredient>> call, #NotNull Throwable t) {
Log.e("the error with", t.toString());
}
});
}
public void onItemSelected (String s) {
Chip chip = new Chip(this);
chip.setText(s);
chip.setCloseIconVisible(true);
chip.setCheckable(false);
chip.setClickable(false);
chip.setOnCloseIconClickListener(this);
chipGroup.addView(chip);
}
#Override
public void onClick(View view) {
Chip chip = (Chip) view;
chipGroup.removeView(chip);
}
public void getRecipesByIngredients(String ingredients) {
swipeRefreshLayout.setRefreshing(false);
RecipeApi recipeApi = RetrofitClient.getRecipeApi();
Call<List<Recipe>> ingredientLst = recipeApi.ingredients(ingredients);
ingredientLst.enqueue(new Callback<List<Recipe>>() {
#Override
public void onResponse(#NotNull Call<List<Recipe>> call, #NotNull Response<List<Recipe>> response) {
List<Recipe> recipe = response.body();
recipeList.clear();
for (int i = 0; i < Objects.requireNonNull(recipe).size(); i++) {
recipeList.add(recipe.get(i));
}
swipeRefreshLayout.setRefreshing(false);
RecipeAdapter recipeAdapter = new RecipeAdapter();
recipeAdapter.setMyRecipeList(recipeList);
rv.setAdapter(recipeAdapter);
}
#Override
public void onFailure(#NotNull Call<List<Recipe>> call, #NotNull Throwable t) {
Log.e("Error!...", t.toString());
}
});
}
public String getSelectedChips (#NonNull ChipGroup c) {
StringBuilder res = new StringBuilder();
for (int i = 0; i < c.getChildCount(); i++) {
Chip ch = (Chip) c.getChildAt(i);
String s = ch.getText().toString();
res.append(" , ").append(s);
}
return res.toString();
}
}
![need this](https://i.stack.imgur.com/RLd2U.jpg)
![where i am at them moment](https://i.stack.imgur.com/86giT.jpg)
![I need it like this](https://i.stack.imgur.com/xXQz1.jpg)
![Need an auto select function](https://i.stack.imgur.com/qCb0L.jpg)

how to send spinner data by volley to database

how to send spinner data by volley to database?
The codes are all sent and no problem Only Spinner field is not sent to the data table.
String[] Cat = {"املاک","وسایل نقلیه","لوازم الکترونیکی","مربوط به خانه","خدمات","وسایل شخصی","سرگرمی و فراغت","اجتماعی","برای کسب و کار","استخدام و کاریابی"};
String[] CatCode = {"1","2","3","4","5","6","7","8","9","10"};
String cate = "";
Send Data Class :
String name,description,phone,email,city;
String[] Cat = {"املاک","وسایل نقلیه","لوازم الکترونیکی","مربوط به خانه","خدمات","وسایل شخصی","سرگرمی و فراغت","اجتماعی","برای کسب و کار","استخدام و کاریابی"};
String[] CatCode = {"1","2","3","4","5","6","7","8","9","10"};
String cate = "";
StringRequest AddAdvReq;
private String Post_Url = "http://192.168.1.102/tablo/api/get_new_adv"
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_adv);
defineVolleyCodes();
defineViews();
defineClicks();
ArrayAdapter<String> catAdapter = new ArrayAdapter<>(getApplicationContext(),R.layout.spinner_row,Cat);
SpinCategory.setAdapter(catAdapter);
SpinCategory.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
cate = CatCode[position];
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
cate = CatCode[0];
}
});
}
//==========================
private void defineVolleyCodes() {
AddAdvReq = new StringRequest(Request.Method.POST, Post_Url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Toast.makeText(AddAdv.this, response, Toast.LENGTH_SHORT).show();
finish();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(AddAdv.this, error.toString(), Toast.LENGTH_SHORT).show();
}
}
)
{
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
//Add Post Parameters
String STRImage = getStringImage(bitmap);
params.put("name",name);
params.put("description",description);
params.put("phone",phone);
params.put("email",email);
params.put("city",city);
params.put("category_id",cate);
return params;
}
};
}
//==========================
private void defineViews() {
//===========================Define All EditTexts
ETxtName = (EditText)findViewById(R.id.etxt_name);
ETxtDescription = (EditText)findViewById(R.id.etxt_description);
ETxtPhone = (EditText)findViewById(R.id.etxt_phone);
ETxtEmail = (EditText)findViewById(R.id.etxt_email);
ETxtCity = (EditText)findViewById(R.id.etxt_city);
//==============================Define All Buttons
SpinCategory = (Spinner)findViewById(R.id.spin_category);
//==============================Define All Buttons
BtnAddAdv = (Button)findViewById(R.id.btn_add_adv);
}
//==========================
private void defineClicks() {
BtnAddAdv.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Load Fields
name = ETxtName.getText().toString();
description = ETxtDescription.getText().toString();
phone = ETxtPhone.getText().toString();
email = ETxtEmail.getText().toString();
city = ETxtCity.getText().toString();
cate = SpinCategory.getSelectedItem().toString();
//Add Request To Queue
AppController.getInstance().addToRequestQueue(AddAdvReq);
}
});
}
}
params.put("category_id",cate);
cate = SpinCategory.getSelectedItem().toString();
What's the problem?
Thanks for all.
You are storing the selected item in the variable here
SpinCategory.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
cate = CatCode[position];
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
cate = CatCode[0];
}
});
cate - use it.
In the click listener you override it with the new value from the spinner that may be invalid(I cannot tell you more because I don't see the whole code)
just delete this cate = SpinCategory.getSelectedItem().toString(); line from the BtnAddAdv click listener and try - maybe it will work
Hope it helps.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_adv);
defineVolleyCodes(); // Remove heare
defineViews();
defineClicks(); // Remove heare
ArrayAdapter<String> catAdapter = new ArrayAdapter<>(getApplicationContext(),R.layout.spinner_row,Cat);
SpinCategory.setAdapter(catAdapter);
SpinCategory.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent,
View view, int pos, long id) {
cate = parent.getItemAtPosition().toString();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
defineVolleyCodes();
defineClicks();
}
please set this method call after the SpinCategory as above code mention.
Then in BtnAddAdv cate= cate; in your code.
I hope it'll help you...!

How to add a PLEASE SELECT error to a JSON Spinner

I have an app where you upload images to my company server
I have 2 spinners populated with json data and the selected item in the spinner is passed to an uri.builder for the upload url,
I have seen many questions on SO about setting a please select option on a spinner BUT the please select option of my spinners are coded into my JSON data as an item.
Now what I want is that the app will give an error if that please select item is selected to prompt the user to select a item in the spinner
so to summarize My spinners are populated with json data, the first item in the json data is "Please select" now I want an error message to appear if the please select option is chosen.
public class SecondActivity extends AppCompatActivity implements
View.OnClickListener {
private final int PICK_IMAGE=12345;
private final int REQUEST_CAMERA=6352;
private static final int REQUEST_CAMERA_ACCESS_PERMISSION=5674;
private Bitmap bitmap;
private ImageView imageView;
String myURL;
Spinner spinner;
Spinner spinner2;
String URL;
String URL2;
ArrayList<String> CategoryName;
ArrayList<String> ClientName;
String Item;
String Item2;
String email;
String clientId;
String pwd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
imageView=findViewById(R.id.imageView);
Button fromCamera=findViewById(R.id.fromCamera);
Button fromGallery=findViewById(R.id.fromGallery);
Button upload=findViewById(R.id.upload);
CategoryName=new ArrayList<>();
ClientName=new ArrayList<>();
spinner=findViewById(R.id.spinner);
spinner2=findViewById(R.id.spinner2);
email = getSharedPreferences("MyPrefs", MODE_PRIVATE).getString("name", "");
clientId= getSharedPreferences("MyPrefs", MODE_PRIVATE).getString("id", "");
pwd= getSharedPreferences("MyPrefs", MODE_PRIVATE).getString("password", "");
CheckBox chk =findViewById(R.id.chk1);
if (chk.isChecked()) {
Uri.Builder builder=new Uri.Builder();
builder.scheme("https")
.authority("www.smartpractice.co.za")
.appendPath("files-upload-phone-app.asp")
.appendQueryParameter("MyForm", "Yes")
.appendQueryParameter("ClientID", clientId)
.appendQueryParameter("Username", email)
.appendQueryParameter("Pwd", pwd)
.appendQueryParameter("Category", Item)
.appendQueryParameter("ClientName", Item2)
.appendQueryParameter("NoEmail", "Yes");
myURL=builder.build().toString();
} else {
Uri.Builder builder=new Uri.Builder();
builder.scheme("https")
.authority("www.smartpractice.co.za")
.appendPath("files-upload-phone-app.asp")
.appendQueryParameter("MyForm", "Yes")
.appendQueryParameter("ClientID", clientId)
.appendQueryParameter("Username", email)
.appendQueryParameter("Pwd", pwd)
.appendQueryParameter("Category", Item)
.appendQueryParameter("ClientName", Item2)
.appendQueryParameter("NoEmail", "Yes");
myURL=builder.build().toString();
}
upload.setOnClickListener(this);
fromCamera.setOnClickListener(this);
fromGallery.setOnClickListener(this);
Uri.Builder builder=new Uri.Builder();
builder.scheme("https")
.authority("www.smartpractice.co.za")
.appendPath("app-categories.asp")
.appendQueryParameter("MyForm", "Yes")
.appendQueryParameter("ClientID",clientId )
.appendQueryParameter("Username",email )
.appendQueryParameter("Pwd",pwd );
URL=builder.build().toString();
Uri.Builder builder2=new Uri.Builder();
builder2.scheme("https")
.authority("www.smartpractice.co.za")
.appendPath("app-clients.asp")
.appendQueryParameter("MyForm", "Yes")
.appendQueryParameter("ClientID",clientId )
.appendQueryParameter("Username",email )
.appendQueryParameter("Pwd",pwd );
URL2=builder2.build().toString();
loadSpinnerData(URL);
loadSpinnerData2(URL2);
spinner 1 on item selection code
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
{
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
String country=spinner.getItemAtPosition(spinner.getSelectedItemPosition()).toString();
Toast.makeText(getApplicationContext(), country, Toast.LENGTH_LONG).show();
Item=spinner.getSelectedItem().toString();
spinner.getSelectedItemPosition();
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
Spinner 2 on itme selection code
spinner2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
String country=spinner2.getItemAtPosition(spinner2.getSelectedItemPosition()).toString();
Toast.makeText(getApplicationContext(), country, Toast.LENGTH_LONG).show();
Item2=spinner2.getSelectedItem().toString();
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
}
}
spinner 1 code for loading the JSON data from the server
private void loadSpinnerData(String url) {
RequestQueue requestQueue=Volley.newRequestQueue(getApplicationContext());
StringRequest stringRequest=new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject=new JSONObject(response);
if (jsonObject.getInt("success") == 1) {
JSONArray jsonArray=jsonObject.getJSONArray("Name");
for (int i=0; i < jsonArray.length(); i++) {
JSONObject jsonObject1=jsonArray.getJSONObject(i);
String country=jsonObject1.getString("Category");
CategoryName.add(country);
}
}
spinner.setAdapter(new ArrayAdapter<>(SecondActivity.this, android.R.layout.simple_spinner_dropdown_item, CategoryName));
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
int socketTimeout=30000;
RetryPolicy policy=new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
stringRequest.setRetryPolicy(policy);
requestQueue.add(stringRequest);
}
Code for spinner 2 to load JSON data from the server
private void loadSpinnerData2(String url) {
RequestQueue requestQueue=Volley.newRequestQueue(getApplicationContext());
StringRequest stringRequest=new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject=new JSONObject(response);
if (jsonObject.getInt("success") == 1) {
JSONArray jsonArray=jsonObject.getJSONArray("Name");
for (int i=0; i < jsonArray.length(); i++) {
JSONObject jsonObject1=jsonArray.getJSONObject(i);
String clientName=jsonObject1.getString("ClientName");
ClientName.add(clientName);
}
}
spinner2.setAdapter(new ArrayAdapter<>(SecondActivity.this, android.R.layout.simple_spinner_dropdown_item, ClientName));
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
int socketTimeout=30000;
RetryPolicy policy=new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
stringRequest.setRetryPolicy(policy);
requestQueue.add(stringRequest);
}
Add the following line to top of your onItemSelected Method of Spinner.
if(i==0){
///Here you need to show the error msg for the first item selected
Log.v("ERROR","Please select an item callded");
//return is used the break the flow of the app so the code below does not run in this case
return;
}
Add your item at first position. Add an Item Selected Check Listner on Spinner and add a check if selected value is first. If first then show a message
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
// your code here
if(position==0)
Toast.makeText(getContext,"Please select a value",Toast.LENGTH_LONG).show()
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
// your code here
}
});

App is not responding after running this activity

New Activity UI load but does not respond, After running onStop() which trigger submit()
List View with the checkbox is bound by a custom adapter. On touch of the Submit button, an intent is triggered which takes me to HomeActivity and onStop() method is triggered which in return call submit method. All submit method is created under a new thread which interfere with UI.
package com.example.cadur.teacher;
public class Attendace extends AppCompatActivity {
DatabaseReference dref;
ArrayList<String> list=new ArrayList<>();
ArrayList<DeatailAttandance> deatailAttandances;
private MyListAdapter myListAdapter;
private ProgressDialog pb;
String year,branch,subject,emailId,pre,abs,rollno,file_name,dat,dat1,roll_str,rollno_present="",rollno_absent="";
int pre_int,abs_int;
ListView listview;
FirebaseDatabase database;
DatabaseReference myRef;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferences sp=getSharedPreferences("login",MODE_PRIVATE);
final String s=sp.getString("Password","");
final String s1=sp.getString("username","");
year=sp.getString("Year","");
branch=sp.getString("Branch","");
subject=sp.getString("Subject","");
final String attend="Attandence";
emailId=sp.getString("emailId","");
if (s!=null&&s!="" && s1!=null&&s1!="") {
setContentView(R.layout.activity_attendace);
deatailAttandances=new ArrayList<>();
listview = findViewById(R.id.list);
TextView detail=findViewById(R.id.lay);
detail.setText(year+" "+branch+" "+" "+subject);
pb =new ProgressDialog(Attendace.this);
pb.setTitle("Connecting Database");
pb.setMessage("Please Wait....");
pb.setCancelable(false);
pb.show();
database=FirebaseDatabase.getInstance();
myRef=database.getReference(year+"/"+branch);
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds:dataSnapshot.getChildren()) {
try {
abs = ds.child("Attandence").child(subject).child("Absent").getValue().toString();
pre = ds.child("Attandence").child(subject).child("Present").getValue().toString();
rollno = ds.getKey().toString();
deatailAttandances.add(new DeatailAttandance(rollno,pre,abs));
myListAdapter=new MyListAdapter(Attendace.this,deatailAttandances);
listview.setAdapter(myListAdapter);
pb.dismiss();
}catch (NullPointerException e){
pb.dismiss();
Intent intent=new Intent(Attendace.this, Login.class);
startActivity(intent);
finish();
}
}
count();
}
#Override
public void onCancelled(DatabaseError error) {
// Failed to read value
}
});
Button selectAll=findViewById(R.id.selectall);
selectAll.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
myListAdapter.setCheck();
count();
}
});
Button submit_attan=findViewById(R.id.submit_attan);
submit_attan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent =new Intent(Attendace.this,HomeActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
});
Button count=findViewById(R.id.count);
count.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
View parentView = null;
int counter=0;
for (int i = 0; i < listview.getCount(); i++) {
parentView = getViewByPosition(i, listview);
CheckBox checkBox=parentView.findViewById(R.id.ch);
if(checkBox.isChecked()){
counter++;
}
}
Toast.makeText(Attendace.this,""+counter,Toast.LENGTH_SHORT).show();
}
});
}else{
SharedPreferences.Editor e = sp.edit();
e.putString("Password", "");
e.putString("username", "");
e.commit();
Intent i=new Intent(Attendace.this,MainActivity.class);
startActivity(i);
finish();
}
}
#Override
protected void onStop() {
Attendace.this.runOnUiThread(new Runnable() {
#Override
public void run() {
submit();
}
});
finish();
super.onStop();
}
public void submit(){
View parentView = null;
final Calendar calendar = Calendar.getInstance();
dat=new SimpleDateFormat("dd_MMM_hh:mm").format(calendar.getTime());
dat1=new SimpleDateFormat("dd MM yy").format(calendar.getTime());
file_name=year+"_"+branch+"_"+dat;
rollno_present=rollno_present+""+year+" "+branch+" "+subject+"\n "+dat+"\n\nList of present Students\n";
rollno_absent=rollno_absent+"\n List of absent Students\n";
for (int i = 0; i < listview.getCount(); i++) {
parentView = getViewByPosition(i, listview);
roll_str = ((TextView) parentView.findViewById(R.id.text1)).getText().toString();
String pre_str = ((TextView) parentView.findViewById(R.id.text22)).getText().toString();
String abs_str = ((TextView) parentView.findViewById(R.id.text33)).getText().toString();
pre_int=Integer.parseInt(pre_str);
abs_int=Integer.parseInt(abs_str);
CheckBox checkBox=parentView.findViewById(R.id.ch);
if(checkBox.isChecked()){
pre_int++;
myRef.child(roll_str).child("Attandence").child(subject).child("Present").setValue(""+pre_int);
myRef.child(roll_str).child("Attandence").child(subject).child("Date").child(dat1).setValue("P");
rollno_present=rollno_present+"\n"+roll_str+"\n";
}else{
abs_int++;
myRef.child(roll_str).child("Attandence").child(subject).child("Absent").setValue(""+abs_int);
myRef.child(roll_str).child("Attandence").child(subject).child("Date").child(dat1).setValue("A");
rollno_absent=rollno_absent+"\n"+roll_str+"\n";
}
}
// Toast.makeText(Attendace.this,"Attendance Updated Successfully",Toast.LENGTH_SHORT).show();
AsyncTask.execute(new Runnable() {
#Override
public void run() {
generateNoteOnSD(Attendace.this,file_name,rollno_present+""+rollno_absent);
}
});
}
public void count(){
View parentView = null;
int counter=0;
for (int i = 0; i < listview.getCount(); i++) {
parentView = getViewByPosition(i, listview);
CheckBox checkBox=parentView.findViewById(R.id.ch);
if(checkBox.isChecked()){
counter++;
}
}
Toast.makeText(Attendace.this,""+counter,Toast.LENGTH_SHORT).show();
}
private View getViewByPosition(int pos, ListView listview1) {
final int firstListItemPosition = listview1.getFirstVisiblePosition();
final int lastListItemPosition = firstListItemPosition + listview1.getChildCount() - 1;
if (pos < firstListItemPosition || pos > lastListItemPosition) {
return listview1.getAdapter().getView(pos, null, listview1);
} else {
final int childIndex = pos - firstListItemPosition;
return listview1.getChildAt(childIndex);
}
}
public void generateNoteOnSD(Context context, String sFileName, String sBody) {
try
{
File root = new File(Environment.getExternalStorageDirectory(),year+"_"+branch+"_Attendance");
if (!root.exists())
{
root.mkdirs();
}
File gpxfile = new File(root, file_name+".doc");
FileWriter writer = new FileWriter(gpxfile,true);
writer.append(sBody+"\n");
writer.flush();
writer.close();
// Toast.makeText(Attendace.this,"File Generated",Toast.LENGTH_SHORT).show();
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
Just use
submit();
instead of using
Attendace.this.runOnUiThread(new Runnable() {
#Override
public void run() {
submit();
}
});
and remove finish()

How to pass value from recyclerview item to another activity

I'm trying to pass the value in recyclerview item to another activity when we click the recyclerview item. Here I use the OnItemTouchListener.
I retrieve data from JSON and parse it into ArrayList. I save 5 parameters. Title, ID, Rating, ReleaseDate, urlPoster, but right now i only show 2 parameters, Title, and image from urlposter.
I want to pass the other parameters to another activity, but i can't find out how to do that.
There's another question similar like this (Values from RecyclerView item to other Activity), but he uses OnClick, not OnItemTouch, and he do that in the ViewHolder. I read somewhere in the internet that it's not the right thing to do.
Here's my code
public class Tab1 extends Fragment {
private static final String ARG_PAGE = "arg_page";
private static final String STATE_MOVIES = "state movies";
private TextView txtResponse;
private String passID;
// Progress dialog
private ProgressDialog pDialog;
//private String urlJsonArry = "http://api.androidhive.info/volley/person_array.json";
private String urlJsonArry = "http://api.themoviedb.org/3/movie/popular?api_key=someapikeyhere";
private String urlJsonImg = "http://image.tmdb.org/t/p/w342";
// temporary string to show the parsed response
private String jsonResponse = "";
RecyclerView mRecyclerView;
RecyclerView.LayoutManager mLayoutManager;
RecyclerView.Adapter mAdapter;
private ArrayList<Movies> movies = new ArrayList<Movies>();
public Tab1() {
// Required empty public constructor
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelableArrayList(STATE_MOVIES, movies);
}
public static Tab1 newInstance(int pageNumber){
Tab1 myFragment = new Tab1();
Bundle arguments = new Bundle();
arguments.putInt(ARG_PAGE, pageNumber);
myFragment.setArguments(arguments);
return myFragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
}
/**
* Method to make json object request where json response starts wtih {
* */
private void makeJsonObjectRequest() {
showpDialog();
final JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(urlJsonArry, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
//Log.d(TAG, response.toString());
try {
JSONArray result = response.getJSONArray("results");
//Iterate the jsonArray and print the info of JSONObjects
for(int i=0; i < result.length(); i++){
JSONObject jsonObject = result.getJSONObject(i);
String id = jsonObject.getString("id");
String originalTitle = jsonObject.getString("original_title");
String releaseDate = jsonObject.getString("release_date");
String rating = jsonObject.getString("vote_average");
String urlThumbnail = urlJsonImg + jsonObject.getString("poster_path");
//jsonResponse = "";
jsonResponse += "ID: " + id + "\n\n";
jsonResponse += "Title: " + originalTitle + "\n\n";
jsonResponse += "Release Date: " + releaseDate + "\n\n";
jsonResponse += "Rating: " + rating + "\n\n";
}
//Toast.makeText(getActivity(),"Response = "+jsonResponse,Toast.LENGTH_LONG).show();
parseResult(response);
}catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getActivity(),"Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
hidepDialog();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//VolleyLog.d(TAG, "Error: " + error.getMessage());
Toast.makeText(getActivity(),
error.getMessage(), Toast.LENGTH_SHORT).show();
// hide the progress dialog
hidepDialog();
}
});
// Adding request to request queue
VolleySingleton.getInstance(getActivity()).addToRequestQueue(jsonObjectRequest);
}
private void showpDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
private void hidepDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
//txtResponse = (TextView) getActivity().findViewById(R.id.txtResponse);
//makeJsonArrayRequest();
// Calling the RecyclerView
mRecyclerView = (RecyclerView) getActivity().findViewById(R.id.recycler_view_movie);
mRecyclerView.setHasFixedSize(true);
// The number of Columns
mLayoutManager = new GridLayoutManager(getActivity(),2);
mRecyclerView.setLayoutManager(mLayoutManager);
mAdapter = new MovieAdapter(getActivity(),movies);
mRecyclerView.setAdapter(mAdapter);
mRecyclerView.addOnItemTouchListener(new RecyclerTouchListener(getActivity(), mRecyclerView, new ClickListener() {
#Override
public void onMovieClick(View view, int position) {
Toast.makeText(getActivity(), "Kepencet " + position, Toast.LENGTH_SHORT).show();
**//what to do here?**
}
#Override
public void onMovieLongClick(View view, int position) {
Toast.makeText(getActivity(),"Kepencet Lama "+position,Toast.LENGTH_LONG).show();
}
}));
makeJsonObjectRequest();
if (savedInstanceState!=null){
movies=savedInstanceState.getParcelableArrayList(STATE_MOVIES);
mAdapter.notifyDataSetChanged();
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.tab_1, container, false);
return view;
}
private void parseResult(JSONObject response) {
try {
JSONArray arrayMovies = response.getJSONArray("results");
if (movies == null) {
movies = new ArrayList<Movies>();
}
for (int i = 0; i < arrayMovies.length(); i++) {
JSONObject currentMovies = arrayMovies.getJSONObject(i);
Movies item = new Movies();
item.setTitle(currentMovies.optString("original_title"));
item.setRating(currentMovies.optString("vote_average"));
item.setReleaseDate(currentMovies.optString("release_date"));
item.setId(currentMovies.optString("id"));
item.setUrlThumbnail(urlJsonImg+currentMovies.optString("poster_path"));
movies.add(item);
mAdapter.notifyDataSetChanged();
//Toast.makeText(getActivity(),"Movie : "+movies,Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
class RecyclerTouchListener implements RecyclerView.OnItemTouchListener{
private GestureDetector mGestureDetector;
private ClickListener mClickListener;
public RecyclerTouchListener(final Context context, final RecyclerView recyclerView, final ClickListener clickListener) {
this.mClickListener = clickListener;
mGestureDetector = new GestureDetector(context,new GestureDetector.SimpleOnGestureListener(){
#Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
#Override
public void onLongPress(MotionEvent e) {
View child = recyclerView.findChildViewUnder(e.getX(),e.getY());
if (child!=null && clickListener!=null){
clickListener.onMovieLongClick(child,recyclerView.getChildAdapterPosition(child));
}
super.onLongPress(e);
}
});
}
#Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
View child = rv.findChildViewUnder(e.getX(), e.getY());
if (child!=null && mClickListener!=null && mGestureDetector.onTouchEvent(e)){
mClickListener.onMovieClick(child,rv.getChildAdapterPosition(child));
}
return false;
}
#Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
}
public static interface ClickListener{
public void onMovieClick(View view, int position);
public void onMovieLongClick(View view, int position);
}
}
any help would be appreciated. Thanks!
You need to add those other two values to a bundle in the intent. So something like this:
Intent intent = new Intent(getActivity(), YourNextActivity.class);
intent.putExtra("movie_id_key", movies.get(position).getId); //you can name the keys whatever you like
intent.putExtra("movie_rating_key", movies.get(position).getRating); //note that all these values have to be primitive (i.e boolean, int, double, String, etc.)
intent.putExtra("movie_release_date_key", movies.get(position).getReleaseDate);
startActivity(intent)
And in your new activity just do this to retrieve:
String id = getIntent().getExtras().getString("movie_id_key");
Add them as extras in the intent with which you start the activity:
Intent intent = new Intent(currentActivity, targetActivity);
// Sree was right in his answer, it's putExtra, not putStringExtra. =(
intent.putExtra("title", title);
// repeat for ID, Rating, ReleaseDate, urlPoster
startActivity(intent);
then pull them out in the onCreate of the other activity with
Intent startingIntent = getIntent();
String title = startingIntent.getStringExtra("title"); // or whatever.
In response to the comment below:
I'm not 100% sure how you implemented it, but it looks like you have onclick handlers that pass a position and a view reference, right? Adapt it as you like, but basically...:
public void onClick(View v, int position){
Movie m = movies.get(position);
Intent intent = new Intent(v.getContext(), AnotherActivity.class);
intent.putExtra("my_movie_foo_key", m.getFoo());
intent.putExtra("my_movie_bar_key", m.getBar());
// etc.
v.getContext().startActivity(intent);
}
As long as you have a valid context reference (and they couldn't click on a view without a valid context), you can start an activity from wherever you like.

Categories

Resources