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
}
});
Related
I am using Depandent Spinner in android studio. They are working well The child spinner is showing the correct data of against selected value of parent spinner but when I pass spinner text to Firebase Realtime database, it only pases the text of first index of childcat(child spinner), even when other item is selected. Text of main cat(parent spinner) is passing well in firebase database.
Here is the code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_up);
emailtext = findViewById(R.id.emailtext);
// category = findViewById(R.id.cat);
fname = findViewById(R.id.fullnametext);
organization = findViewById(R.id.org);
maincat = findViewById(R.id.categories);
childcat = findViewById(R.id.categoryitem);
signup = findViewById(R.id.btn_signup);
ArrayAdapter adp1=ArrayAdapter.createFromResource(this, R.array.Categories,R.layout.support_simple_spinner_dropdown_item);
adp1.setDropDownViewResource(R.layout.support_simple_spinner_dropdown_item);
maincat.setAdapter(adp1);
maincat.setOnItemSelectedListener(this);
signup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String email = emailtext.getText().toString();
// final String fcategory = category.getText().toString();
final String name = fname.getText().toString();
//final String con_pass = organization.getText().toString();
final String cat=category;
final String subcat=specific;
Map<String, Object> Users = new HashMap<>();
Users.put("Name", name);
Users.put("Email", email);
Users.put("Category", cat);
Users.put("SubCategory", subcat);
FirebaseDatabase.getInstance().getReference().child("Users").push().setValue(Users).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
Log.i("vvv", "oncomplete");
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.i("nnn", "OnFailure:" + e.toString());
}
});
}
});
;
}
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
category=maincat.getSelectedItem().toString();
if(i==0){
ArrayAdapter adp2 = ArrayAdapter.createFromResource(this, R.array.Natural_Disasters, R.layout.support_simple_spinner_dropdown_item);
childcat.setAdapter(adp2);
}
if(i==1){
ArrayAdapter adp2 = ArrayAdapter.createFromResource(this, R.array.Medical, R.layout.support_simple_spinner_dropdown_item);
childcat.setAdapter(adp2);
}
if(i==2){
ArrayAdapter adp2 = ArrayAdapter.createFromResource(this, R.array.Events, R.layout.support_simple_spinner_dropdown_item);
childcat.setAdapter(adp2);
}
if(i==3){
ArrayAdapter adp2 = ArrayAdapter.createFromResource(this, R.array.Career_supporting, R.layout.support_simple_spinner_dropdown_item);
childcat.setAdapter(adp2);
}
if(i==4){
ArrayAdapter adp2 = ArrayAdapter.createFromResource(this, R.array.SocialIssues, R.layout.support_simple_spinner_dropdown_item);
childcat.setAdapter(adp2);
}
specific=childcat.getSelectedItem().toString();
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
}
add these 3 lines in on create
ProgressDialog mDialog = new ProgressDialog(getApplicationContext());
mDialog.setMessage("Please wait...");
mDialog.setCancelable(false);
add two lines in your signup function
mDialog.show(); //to show activity indicator
mDialog. dismiss(); //to hide activity indicator
here is example with your code
signup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String email = emailtext.getText().toString();
// final String fcategory = category.getText().toString();
final String name = fname.getText().toString();
//final String con_pass = organization.getText().toString();
final String cat=category;
final String subcat=specific;
Map<String, Object> Users = new HashMap<>();
Users.put("Name", name);
Users.put("Email", email);
Users.put("Category", cat);
Users.put("SubCategory", subcat);
mDialog.show();//to show activity indicator
FirebaseDatabase.getInstance().getReference().child("Users").push().setValue(Users).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
mDialog. dismiss();//to hide activity indicator
Log.i("vvv", "oncomplete");
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.i("nnn", "OnFailure:" + e.toString());
}
});
}
});
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...!
public class MainActivity extends AppCompatActivity implements
Response.Listener<JSONObject>,
Response.ErrorListener,
AdapterView.OnItemClickListener {
EditText movienameText;
Button getButton;
TextView yearText,genreText,titleText,plotText,nameText;
ListView moviesList;
private ResourceBundle response;
ArrayAdapter<String> adapter;
ArrayList<String>moviesname=new ArrayList<String>();
ArrayList<String>moviesyear=new ArrayList<String>();
ArrayList<String>moviesgenre=new ArrayList<String>();
ArrayList<String>moviesplot=new ArrayList<String>();
String x,plot,genre,year;
RequestQueue queue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
movienameText=findViewById(R.id.MovienameText);
getButton=findViewById(R.id.getButton);
moviesList=findViewById(R.id.moviesList);
moviesList.setOnItemClickListener(this);
adapter=newArrayAdapter<String(this,android.R.layout.
simple_list_item_1, moviesname);
}
public void get(View view) {
queue = Volley.newRequestQueue(this);
String url1="http://www.omdbapi.com
/?s="+movienameText.getText().toString()+"&apikey=1a382b30";
JsonObjectRequest request1=new
JsonObjectRequest(Request.Method.GET,url1,null,this,this);
queue.add(request1);
}
#Override
public void onResponse(JSONObject response) {
try {
for (int i = 0; i <response.getJSONArray("Search").length(); i++) {
if (i<response.getJSONArray("Search").length()){
moviesname.add(response.getJSONArray("Search").getJSONObject(i)
.getString("Title"));
}
else{
break;
}
}
moviesList.setAdapter(adapter);
year=response.getString("Year");
} catch (JSONException e) {
Toast.makeText(this, "error", Toast.LENGTH_SHORT).show();
e.printStackTrace();
} }
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(this, "error", Toast.LENGTH_SHORT).show(); }
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
year=response.getString("Year");
x = moviesList.getItemAtPosition(position).toString();
String url2="http://www.omdbapi.com
/?t="+moviesList.getItemAtPosition(position).toString().replace("
","")+"&apikey=1a382b30";
JsonObjectRequest request2=new
JsonObjectRequest(Request.Method.GET,url2,null,this,this);
queue.add(request2);
AlertDialog.Builder builder=new AlertDialog.Builder(this);
builder.setMessage(x).create().show();
builder.setMessage(year).create().show(); // builder.setMessage(genre).create().show(); // builder.setMessage(plot).create().show();
}
}
when I type a movie name with two words like(die hard) it Enters on error method, but I don't know why?..................................................................................................................................................................................................................................
Probably you have to encode your movienameText.getText(). Http links don't allow spaces.
Try to do:
String url1 = TextUtils.htmlEncode("http://www.omdbapi.com/?s="+movienameText.getText().toString()+"&apikey=1a382b30");
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.
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.