how do I setText value when I on click button? - android

how do I setText value when I on click button?
now, I can get the value from my DB, but how can set text when I click the button?
private JsonArrayRequest getDataFromServer(int requestCount) {
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Load...");
final String DATA_URL = "https://aaa.ccc/eee.php";
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(DATA_URL,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
parseData(response);
progressDialog.dismiss();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressDialog.dismiss();
}
});
return jsonArrayRequest;
}
private void loadTravelRule() {
requestQueue.add(getDataFromServer(requestCount));
requestCount++;
}
private void parseData(JSONArray array) {
for (int i = 0; i < array.length(); i++) {
TravelRuleModel travelRuleModel = new TravelRuleModel();
JSONObject json = null;
try {
json = array.getJSONObject(i);
String TAG_TravelRule = "TravelRule";
travelRuleModel.setTravelrule(json.getString(TAG_TravelRule));
} catch (JSONException e) {
e.printStackTrace();
}
travelRuleModels.add(travelRuleModel);
}
}
I can get json.getString(TAG_TravelRule) value, but I want to set value in here.
tips.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
BottomSheetDialog bottomSheetDialog = new BottomSheetDialog(MainActivity.this, R.style.BottomSheetDialogTheme);
View bottomSheetView = LayoutInflater.from(getApplicationContext()).inflate(R.layout.tips, (LinearLayout)findViewById(R.id.bottomSheetContainer));
travel_rule = findViewById(R.id.travel_rule);
// Can I set value to R.id.travel_rule in R.layout.tips???
if it is can set value how can I do?
bottomSheetDialog.setContentView(bottomSheetView);
bottomSheetDialog.show();
}
});
I tried to used
rule = json.getString(TAG_TravelRule);
then
travel_rule.setText(rule);
but I got null

I suppose the textview is on the bottomSheetView xml so you have to reference that to find your textview
travel_rule = bottomSheetView.findViewById(R.id.travel_rule);

Related

Get selected item from first spinner and send to string request URL

I have tried send selected item from first spinner and i want second spinner show if first spinner selected and send data to string request URL but failed. Example I've been selected number 1 on first spinner and second spinner showing based string URL which already send from first. like this http://192.168.43.66/json/kota/1 and more
public String DataIDProvinsi;
private ArrayList<String>id_provinsi;
private ArrayList<String>nama_provinsi;
private ArrayList<String>id_kota;
private ArrayList<String>nama_kota;
private ArrayList<String>id_kecamatan;
private ArrayList<String>nama_kecamatan;
private JSONArray result;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
nama_provinsi = new ArrayList<String>();
id_provinsi = new ArrayList<String>();
id_kota = new ArrayList<String>();
nama_kota = new ArrayList<String>();
TxtDataProvinsi = (EditText) findViewById(R.id.TxtDataProvinsi);
spinner_provinsi = (Spinner) findViewById(R.id.spinner_provinsi);
spinner_kota = (Spinner) findViewById(R.id.spinner_kota);
spinner_jk = (Spinner) findViewById(R.id.spinner_jk);
TxtIdProvinsi = (TextView) findViewById(R.id.TxtIdProvinsi);
spinner_provinsi.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?>parent, View view, int position, long id){
}
#Override
public void onNothingSelected(AdapterView<?>parent){
TxtIdProvinsi.setText("");
}
});
spinner_kota.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?>parent, View view, int position, long id){
}
#Override
public void onNothingSelected(AdapterView<?>parent){
}
});
TxtIdKota = (TextView) findViewById(R.id.TxtIdKota);
TxtTglLhr = findViewById(R.id.TxtTglLahir);
findViewById(R.id.TxtTglLahir).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showDatePickerDialog();
}
});
getDataProvinsi();
getDataKota();
}
private void showDatePickerDialog(){
DatePickerDialog datePickerDialog = new DatePickerDialog(this,
this, Calendar.getInstance().get(Calendar.YEAR),
Calendar.getInstance().get(Calendar.MONTH),
Calendar.getInstance().get(Calendar.DAY_OF_MONTH));
datePickerDialog.show();
}
#Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
String tanggal = year+"-"+month+"-"+dayOfMonth;
TxtTglLhr.setText(tanggal);
}
public void getDataProvinsi(){
pDialog = new ProgressDialog(RegisterActivity.this);
pDialog.setCancelable(false);
pDialog.setMessage("Mohon Menunggu...");
// showDialog();
StringRequest stringRequestProvinsi = new StringRequest("http://192.168.43.66/json/provinsi/", new Response.Listener<String>() {
#Override
public void onResponse(String response) {
JSONObject j = null;
try {
j = new JSONObject(response);
result = j.getJSONArray("result");
getNamaProvinsi(result);
} catch (JSONException e) {
e.printStackTrace();
}
// hideDialog();
}
},
new Response.ErrorListener(){
#Override
public void onErrorResponse(VolleyError error){
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequestProvinsi);
}
public void getDataKota(){
DataIDProvinsi = spinner_provinsi.getSelectedItem().toString();
StringRequest stringRequestKota = new StringRequest("http://192.168.43.66/json/kota/"+DataIDProvinsi, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
JSONObject j = null;
try {
j = new JSONObject(response);
result = j.getJSONArray("result");
getNamaKota(result);
} catch (JSONException e) {
e.printStackTrace();
}
// hideDialog();
}
},
new Response.ErrorListener(){
#Override
public void onErrorResponse(VolleyError error){
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequestKota);
}
public void getNamaProvinsi(JSONArray j){
for (int i = 0; i < j.length(); i++){
try {
JSONObject jsonProvinsi = j.getJSONObject(i);
id_provinsi.add(jsonProvinsi.getString("id_provinsi"));
//nama_provinsi.add(jsonProvinsi.getString(ProvinsiActivity.TAG_NAMA_PROVINSI));
} catch (JSONException e) {
e.printStackTrace();
}
}
spinner_provinsi.setAdapter(new ArrayAdapter<String>(RegisterActivity.this,
R.layout.support_simple_spinner_dropdown_item, id_provinsi));
}
public void getNamaKota(JSONArray j){
for (int i = 0; i < j.length(); i++){
try {
JSONObject jsonKota = j.getJSONObject(i);
//id_kota.add(jsonKota.getString(KotaActivity.TAG_ID_KOTA));
nama_kota.add(jsonKota.getString("nama_kota"));
} catch (JSONException e) {
e.printStackTrace();
}
}
spinner_kota.setAdapter(new ArrayAdapter<String>(RegisterActivity.this,
R.layout.support_simple_spinner_dropdown_item, nama_kota));
}
private void showDialog(){
if(!pDialog.isShowing())
pDialog.show();
}
private void hideDialog(){
if(pDialog.isShowing())
pDialog.dismiss();
}
}

I am using recreate() to refresh but why does it double refresh?

I am using recreate and refresh() to refresh page every minute but it double refreshes. First refresh is after 1minute, and the next refresh is after 2 sec first refresh.
i have tried changing the code inside refresh but didnt work.
private void loadalltrolley(){
StringRequest stringRequest = new StringRequest(Request.Method.GET, PRODUCT_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray products = new JSONArray(response);
for(int i =0;i<products.length();i++){
JSONObject productObject = products.getJSONObject(i);
String gate_no = productObject.getString("gate_no");
String dock_name = productObject.getString("dock_name");
String dock_desc = productObject.getString("dock_desc") ;
int flight_arrival = productObject.getInt("flight_arrival");
int trolley_count = productObject.getInt("trolley_count");
Product product = new Product(gate_no,dock_name,dock_desc,flight_arrival,trolley_count);
allterminalList.add(product);
}
allterminaladapter = new ProductAdapter(alert.this,allterminalList);
recyclerView.setAdapter(allterminaladapter);
int count = allterminaladapter.getItemCount();
int i =0;
if (count>0)
{
displayNotification();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(alert.this,error.getMessage(),Toast.LENGTH_SHORT).show();
}
});
Volley.newRequestQueue(this).add(stringRequest);
refresh(60000);
}
public void refresh(int milliseconds){
final Handler handler = new Handler();
final Runnable runnable = new Runnable() {
#Override
public void run() {
recreate();
}
};
handler.postDelayed(runnable,milliseconds);
}
I want it to refresh 1 time only and not double refresh. I want to refresh the application after 1minute only.

why do my recyclerview have 2 rows of the same data when its selected from spinner?

I have a Spinner and a RecyclerView and the RecyclerView is used to display the data that I fetch from the database but the on RecyclerView, I have 2 rows of the same thing when I select the second option on the Spinner.
I have tried switch loop, changing adapter and changing api url.
Spinner spinner = (Spinner) findViewById(R.id.spinner);
adapterspinner = ArrayAdapter.createFromResource(this,R.array.planets_array,android.R.layout.simple_spinner_item);
adapterspinner.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapterspinner);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
if(i==0)
{
loadt1trolley();
}
if(i==1)
{
loadalltrolley();
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
private void loadalltrolley(){
StringRequest stringRequest = new StringRequest(Request.Method.GET, PRODUCT_URL,new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray products = new JSONArray(response);
for(int i =0;i<products.length();i++){
JSONObject productObject = products.getJSONObject(i);
String gate_no = productObject.getString("gate_no");
String dock_name = productObject.getString("dock_name");
String dock_desc = productObject.getString("dock_desc") ;
int flight_arrival = productObject.getInt("flight_arrival");
int trolley_count = productObject.getInt("trolley_count");
Product product = new Product(gate_no,dock_name,dock_desc,flight_arrival,trolley_count);
allterminalList.add(product);
}
allterminaladapter = new ProductAdapter(alert.this,allterminalList);
recyclerView.setAdapter(allterminaladapter);
int count = allterminaladapter.getItemCount();
int i =0;
if (count>0)
{
displayNotification();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(alert.this,error.getMessage(),Toast.LENGTH_SHORT).show();
}
});
Volley.newRequestQueue(this).add(stringRequest);
refresh(6000);
}
private void loadt1trolley(){
StringRequest stringRequest1 = new StringRequest(Request.Method.GET, T1_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray products = new JSONArray(response);
for(int i =0;i<products.length();i++){
JSONObject productObject = products.getJSONObject(i);
String gate_no = productObject.getString("gate_no");
String dock_name = productObject.getString("dock_name");
String dock_desc = productObject.getString("dock_desc") ;
int flight_arrival = productObject.getInt("flight_arrival");
int trolley_count = productObject.getInt("trolley_count");
Product product = new Product(gate_no,dock_name,dock_desc,flight_arrival,trolley_count);
allterminalList.add(product);
}
allterminaladapter = new ProductAdapter(alert.this,allterminalList);
recyclerView.setAdapter(allterminaladapter);
int count = allterminaladapter.getItemCount();
int i =0;
if (count>0)
{
displayNotification();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(alert.this,error.getMessage(),Toast.LENGTH_SHORT).show();
}
});
Volley.newRequestQueue(this).add(stringRequest1);
refresh(6000);
}
I expect the output to display according to the URL display with 1 row each data but it is displaying 2 row when I press position 1 on spinner
You need to clear allterminalList before making a new network request
allterminalList.clear();
if(i==0)
{
loadt1trolley();
}
else if(i==1)
{
loadalltrolley();
}
Add the code in onItemSelected() method of the Spinner, this should fix the issue.

Not getting newly entered data after swiping the layout

I am using swiperefersh layout here and list view and after swaping, I am not getting new data in my list. I have tried lot of times but not able to dot it. please check my below code where i did mistake. My api is calling on Onrefersh method but not able to find newly entered data. I have searched lot of quotes and answers in google but unable to do it. please help me.
public class ChatActivity extends AppCompatActivity implements SwipeRefreshLayout.OnRefreshListener{
private SwipeRefreshLayout swipeRefreshLayout;
private static final String TAG = "ChatActivity";
String Api_Domain,chatListURL,sendMsgURL;
private ChatArrayApapter chatArrayAdapter;
private ListView listView;
private EditText chatText;
private ImageView buttonSend;
ProgressDialog progrss;
public String group;
public String groupId;
android.support.v7.app.ActionBar groupName;
JSONArray jsonArrayChat;
User user;
Session session;
private int pageCount = 1;
private int entriesPerPage = 20;
private int totalMsgs;
public static Activity reference;
NavigationView navigationView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
reference = this;// do not delete this line
// intialize the views and adapter
swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh_layout);
swipeRefreshLayout.setOnRefreshListener(this);
chatArrayAdapter = new ChatArrayApapter(getApplicationContext(), R.layout.right);
listView.setAdapter(chatArrayAdapter);
chatText = (EditText) findViewById(R.id.msg);
chatText.setOnKeyListener(new View.OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
return sendChatMessage1();
}
return false;
}
});
listView.setTranscriptMode(AbsListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);
listView.setAdapter(chatArrayAdapter);
//listView.setOnScrollListener(onScrollListener());
//to scroll the list view to bottom on data change
chatArrayAdapter.registerDataSetObserver(new DataSetObserver () {
#Override
public void onChanged() {
super.onChanged();
listView.setSelection(chatArrayAdapter.getCount() - 1);
}
});
swipeRefreshLayout.post(new Runnable() {
#Override
public void run() {
swipeRefreshLayout.setRefreshing(true);
getChatList1();
}
}
);
}
// call chat list api
private void getChatList1(){
//if ((chatArrayAdapter.getCount() < totalMsgs && listView.getFirstVisiblePosition()== 0)|| (pageCount==1)) {
RequestQueue mrequestQueue = Volley.newRequestQueue (ChatActivity.this);
StringRequest stringRequest = new StringRequest (Request.Method.POST, chatListURL, new Response.Listener <String> ( ) {
#Override
public void onResponse(String res) {
swipeRefreshLayout.setRefreshing(false);
try {
JSONObject response = new JSONObject (res);
jsonArrayChat = response.getJSONArray("groupchatlist");
if(jsonArrayChat.length()>0){
pageCount++;
}
for (int i = 0; i < jsonArrayChat.length(); i++) {
JSONObject chatObj = (JSONObject) jsonArrayChat.get(i);
if (chatObj.getString("user_emailid").equals(user.email)) {
chatArrayAdapter.add(true,new ChatMessage(false, chatObj.getString("message"), chatObj.getString("username")));
} else {
chatArrayAdapter.add(true,new ChatMessage(true, chatObj.getString("message"), chatObj.getString("username")));
}
}
try {
JSONArray count = response.getJSONArray("totalcount");
JSONObject cnt = (JSONObject) count.get(0);
totalMsgs = cnt.getInt("count(id)");
} catch (JSONException e) {
e.printStackTrace();
totalMsgs = 500;
}
} catch (JSONException e) {
e.printStackTrace ( );
}
}
}, new Response.ErrorListener ( ) {
#Override
public void onErrorResponse(VolleyError error) {
Log.i ("Tag", "Response: " + error.toString ( ));
}
}
) {
#Override
protected Map<String, String> getParams() {
Map <String, String> params = new HashMap<> ( );
//params.put("group", "grp-1");
params.put ("group", groupId);
params.put("pageNo", String.valueOf(pageCount));
params.put("entriesPerPage", String.valueOf(entriesPerPage));
return params;
}
};
mrequestQueue.add (stringRequest);
/*}else{
swipeRefreshLayout.setRefreshing(false);
}*/
}
// refresh method
#Override
public void onRefresh() {
getChatList1();
}
You must call chatArrayAdapter.notifyDataSetChanged() after add all your object into it :
for (int i = 0; i < jsonArrayChat.length(); i++) {
JSONObject chatObj = (JSONObject) jsonArrayChat.get(i);
if (chatObj.getString("user_emailid").equals(user.email)) {
chatArrayAdapter.add(true,new ChatMessage(false, chatObj.getString("message"), chatObj.getString("username")));
} else {
chatArrayAdapter.add(true,new ChatMessage(true, chatObj.getString("message"), chatObj.getString("username")));
}
}
chatArrayAdapter.notifyDataSetChanged() // <-- add this
Try this code after adding data into adapter ..
adpater.notifyDataSetChanged();
There is some response time that Server takes to send you the response.So I'd suggest you to add wait for few milliseconds before hitting again in you Runnable.

Pass position of the item of recycler view to open up a new acitivity

How can i pass the position of item using intent to start a new activity?
I want to start a new activity called single which displays the rating of the movie correspondingly..pls help
I have been trying this for the past two days.
Here is the code:
public class NowPlaying extends Fragment {
private static final String TAG = NowPlaying.class.getSimpleName();
// Movies json url
private static final String url = "http://private-8149-themoviedb.apiary-mock.com/3/movie/now_playing?api_key=";
private ProgressDialog pDialog;
private List<NowPlayingInfo> bottom = new ArrayList<NowPlayingInfo>() ;
NowPlayingAdapter adapter;
RecyclerView recyclerView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.activity_main, container, false);
ActionBar toolbar = ((AppCompatActivity) getActivity()).getSupportActionBar();
toolbar.setTitle("Now playing");
recyclerView = (RecyclerView) v.findViewById(R.id.cardList);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(linearLayoutManager);
adapter = new NowPlayingAdapter(getActivity(), bottom);
recyclerView.setAdapter(adapter);
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Loading...");
pDialog.show();
adapter.SetOnItemClickListener(new NowPlayingAdapter.OnItemClickListener() {
#Override
public void onItemClick(View v, int position) {
// do something with position
Intent i = new Intent(v.getContext(), Single.class);
//pass the position of the item to single class
v.getContext().startActivity(i);
}
});
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
hidePDialog();
try {
JSONArray jsonArray = response.getJSONArray("results");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
NowPlayingInfo trailer = new NowPlayingInfo();
trailer.setTitle(jsonObject.getString("original_title"));
String iss = "http://image.tmdb.org/t/p/w500" + jsonObject.getString("poster_path") ;
trailer.setImage(iss);
bottom.add(trailer);
adapter.notifyDataSetChanged();
}
} catch (JSONException e) {
e.printStackTrace();
}
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
AppController.getInstance().addToRequestQueue(jsonObjectRequest);
return v;
}
#Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
}
adapter.SetOnItemClickListener(new NowPlayingAdapter.OnItemClickListener() {
#Override
public void onItemClick(View v, int position) {
NowPlayingInfo _nowPlaying = bottom.get(position);
// do something with position
Intent i = new Intent(v.getContext(), Single.class);
//pass the position of the item to single class
i.putExtra("ISS", _nowPlaying.getImage()); //you can put your current playing info.
i.putExtra("POSITION", position); //you can put your position to next activity.
v.getContext().startActivity(i);
}
});
Add this in your SingleInfo Class.
String _rating = "";
public String get_rating() {
return _rating;
}
public void set_rating(String _rating) {
this._rating = _rating;
}
Add this in your Single class -
int _currentPos = 0 ; //Global variable .
_currentPos = getIntent().getIntExtra("position", 0);// paste this in onCreate()
Add this code in onResponse of Single Class -
try {
JSONArray jsonArray = response.getJSONArray("results");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
SingleInfo s = new SingleInfo();
s.set_rating(jsonObject.getString("rating"));
single.add(s);
}
//changed by Shoeb
SingleInfo _singleInfo = single.get(_currentPos); //position from previous activity
textView.setText(_singleInfo.get_rating());
//end changes
} catch (JSONException e) {
e.printStackTrace();
}
Add an extra to your intent
i.putExtra("position",position);
And on the other activity:
getIntent().getIntExtra("position", 0);

Categories

Resources