help guys how to display image without using a button, I tried to put it on create but not working and I tried to make it as a function but still not working,but when in button (on click) it show image. I want to show the image without clicking the button.
I want to load the image without clicking the button, so when the user come the image automatically load without push of a button.
public class MainActivity extends AppCompatActivity {
TextView textViewdatashow;
EditText editTextvalue;
ImageView imageView;
Button buttonfetch;
String url ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textViewdatashow = (TextView) findViewById(R.id.tvshowdata);
editTextvalue = (EditText) findViewById(R.id.etvalue);
imageView = (ImageView) findViewById(R.id.image);
buttonfetch = (Button) findViewById(R.id.buttonfetchdata);
buttonfetch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String id = editTextvalue.getText().toString();
url = "https://PASTE_YOUR_IMAGE_URL"+id+".jpg";
getData();
}
});
}
private void getData() {
String id = editTextvalue.getText().toString().trim();
if (id.equals("")) {
Toast.makeText(this, "Check Detail!", Toast.LENGTH_LONG).show();
return;
}
String url = Config.DATA_URL + editTextvalue.getText().toString().trim();
StringRequest stringRequest = new StringRequest(url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
showJSONS(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, error.getMessage().toString(), Toast.LENGTH_LONG).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
private void showJSONS(String response) {
String name = "";
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray result = jsonObject.getJSONArray(Config.JSON_ARRAY);
JSONObject collegeData = result.getJSONObject(0);
name = collegeData.getString(Config.KEY_NAME);
} catch (JSONException e) {
e.printStackTrace();
}
textViewdatashow.setText("" + name);
ImageRetriveWithPicasso();
}
private void ImageRetriveWithPicasso() {
Picasso.get()
.load(url)
.placeholder(R.drawable.imageholder)
.into(imageView);
}
}
Put this code inside on create view
final Handler myHandler = new
Handler(Looper.getMainLooper());
new Thread(new Runnable() {
#Override
public void run() {
myHandler.post(new Runnable() {
#Override
public void run() {
getData()
}
});
}
})).start();
}
Related
I'm new to android studio and I'm trying to create a simple weather app using OpenWeatherMap API. I am using OkHttp library to perform a GET request. All it does is take an input throught EditText and update the TextView on button click using a Button.
But the problem is, the TextView updates after two clicks on the Button. I want to update it right after the first click. So, how do I go over this?
Here is my code:
public class MainActivity extends AppCompatActivity {
private EditText cityName;
private TextView weatherData;
private TextView hiddenText;
private Button getBtn;
public String s = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
weatherData = (TextView)findViewById(R.id.weatherText);
getBtn = (Button)findViewById(R.id.getData);
cityName = (EditText)findViewById(R.id.cityName);
getBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getWeatherData(cityName.getText().toString());
weatherData.setText(s);
}
});
}
public void getWeatherData(String cityText){
String url = "https://api.openweathermap.org/data/2.5/weather?q=" + cityText + "&appid=ba45ceb57328448f7wd666hdc6d57aaf";
OkHttpClient client = new OkHttpClient();
final Request request = new Request.Builder().url(url).build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
s = "Something went wrong!";
}
});
}
#Override
public void onResponse(Call call, final Response response) throws IOException {
if(response.isSuccessful()){
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
try{
s = response.body().string();
}
catch (IOException ioe){
s = "Error while getting JSON.";
}
}
});
}
}
});
}
}
I know that I can update the TextView in onResponse itself but I wanna know if it is possible to update it through onClickListener. If it's not possible, which method should I use? Any help would be appreciated.
you have to update text value in server response call back
public class MainActivity extends AppCompatActivity {
private EditText cityName;
private TextView weatherData;
private TextView hiddenText;
private Button getBtn;
public String s = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
weatherData = (TextView)findViewById(R.id.weatherText);
getBtn = (Button)findViewById(R.id.getData);
cityName = (EditText)findViewById(R.id.cityName);
getBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getWeatherData(cityName.getText().toString());
}
});
}
public void getWeatherData(String cityText){
String url = "https://api.openweathermap.org/data/2.5/weather?q=" + cityText + "&appid=ba45ceb57328448f7wd666hdc6d57aaf";
OkHttpClient client = new OkHttpClient();
final Request request = new Request.Builder().url(url).build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
s = "Something went wrong!";
}
});
}
#Override
public void onResponse(Call call, final Response response) throws IOException {
if(response.isSuccessful()){
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
try{
s = response.body().string();
weatherData.setText(s);
}
catch (IOException ioe){
s = "Error while getting JSON.";
}
}
});
}
}
});
}
}
You are setting data on edit text on click after calling GET Request.
Update the textview with the data , once you get the response.
public class MainActivity extends AppCompatActivity {
private EditText cityName;
private TextView weatherData;
private TextView hiddenText;
private Button getBtn;
public String s = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
weatherData = (TextView)findViewById(R.id.weatherText);
getBtn = (Button)findViewById(R.id.getData);
cityName = (EditText)findViewById(R.id.cityName);
getBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getWeatherData(cityName.getText().toString());
}
});
}
public void getWeatherData(String cityText){
String url = "https://api.openweathermap.org/data/2.5/weather?q=" + cityText + "&appid=ba45ceb57328448f7wd666hdc6d57aaf";
OkHttpClient client = new OkHttpClient();
final Request request = new Request.Builder().url(url).build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
s = "Something went wrong!";
}
});
}
#Override
public void onResponse(Call call, final Response response) throws IOException {
if(response.isSuccessful()){
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
try{
s = response.body().string();
weatherData.setText(s);
}
catch (IOException ioe){
s = "Error while getting JSON.";
}
}
});
}
}
});
}
}
I pass data from MySQL to marquee text in activity one and It works successfully , but I need to send these text to anther activity by intent but not warking for me , Please help
activity One :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dollars);
item_k001 = findViewById(R.id.item_k101);
item_k002 = findViewById(R.id.item_k102);
requestQueue = Volley.newRequestQueue(this);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
final Globalv globalv = (Globalv) getApplicationContext();
try {
JSONArray jsonArray = response.getJSONArray("allegg");
String msg = "";
for (int i = 0; i < response.length(); i++) {
JSONObject respons = jsonArray.getJSONObject(i);
final String myItem_k001 = respons.getString("item_k1");
final String myItem_k002 = respons.getString("item_k2");
DollarsActivity.this.runOnUiThread(new Runnable() {
public void run() {
item_k001.setText(myItem_k001);
item_k002.setText(myItem_k002);
}
});
}
JSONObject respons2 = jsonArray.getJSONObject(0);
String id = respons2.getString("id");
globalv.setTotal_threads(Integer.parseInt(String.valueOf(id)));
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("VOLLEY", "ERROR");
}
}
);
I want to send tow text to activity tow :
//defines variables to the xml elements.
TextView tv1 = (TextView) findViewById(R.id.marqueeTextView1);
TextView tv2 = (TextView) findViewById(R.id.marqueeTextView2);
/// You can change your text here
tv1.setText("Text view");
tv2.setText("Text view ");
// We set the setSelected value to true for the shift of the texts
tv1.setSelected(true);
tv2.setSelected(true);
Please try below code:
Activity 1
intent = new Intent(OneActivity.this, TwoActivity.class);
intent.putExtra("KEY1", myItem_k001);
intent.putExtra("KEY2", myItem_k002);
startActivity(intent);
Activity 2
//In onCreate()
Intent intent = getIntent();
text1 = intent.getStringExtra("KEY1");
text2 = intent.getStringExtra("KEY2")
tv1.setText(text1);
tv2.setText(text2);
if you want to start activity 2 when you get the text, you can can use intent,
but if activity2 was opened later and it is onPouse now,
you can easily use interface :
in sampleInterface:
public interface sampleInterface{
void setText(String text);
}
in activity 1 add:
sampleInterface callBack;
in activity 1 put this into that line that you get your text:
callBack.setText("your Text");
in activity 2:
public class Activity2 extends AppCompatActivity implements ,sampleInterface{
TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_layout_2);
textView= findViewById(R.id.textView);
}
#Override
public void setText(String yourText) {
textView.setText(yourText);
}
}
where ever you call callback.setText("your text here"); this will fire #Override
method in Ativity2 and it return your text
hope this be helpfull
Receive SMS then set EditText to msgBody
public class SmsBroadcastReceiver extends BroadcastReceiver {
//.....
((EditText)MainActivity.mThis.findViewById(R.id.editTextName)).setText(msgBody);}
The error is this in View cannot be applied to android.view.View.Onclicklistiner
//onCreate
buttonSave.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
buttonSave.performClick(this);
}
});
the message will automatically save to SQLite and sync to Mysql when buttonSave is click
private void saveNameToServer() {
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Saving Name...");
progressDialog.show();
final String name = editTextName.getText().toString().trim();
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL_SAVE_NAME,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
progressDialog.dismiss();
try {
JSONObject obj = new JSONObject(response);
if (!obj.getBoolean("error")) {
//if there is a success
//storing the name to sqlite with status synced
saveNameToLocalStorage(name, NAME_SYNCED_WITH_SERVER);
} else {
//if there is some error
//saving the name to sqlite with status unsynced
saveNameToLocalStorage(name, NAME_NOT_SYNCED_WITH_SERVER);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressDialog.dismiss();
//on error storing the name to sqlite with status unsynced
saveNameToLocalStorage(name, NAME_NOT_SYNCED_WITH_SERVER);
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("name", name);
return params;
}
};
VolleySingleton.getInstance(this).addToRequestQueue(stringRequest);
}
#Override
public void onClick(View view) {
saveNameToServer();
}
Are there other ways to auto click button when EditText value changes?
Instead of invoking the click buttonSave.performClick(this); just simply invoke saveNameToServer(); method to save your data.
buttonSave.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
//buttonSave.performClick(this); // remove, not required
saveNameToServer(); // save your data
}
});
I have made a discussion forum where the person who is logged in can ask a question and the main forum shows all the question put up by a different user. everyone can answer the question also and rate.
The problem is when is add the question from adding question activity it is going back to discussion forum but not refreshing. What I want is as soon as the question is asked, it should show in the discussion forum and the user should have the ability to modify and delete that question. everything is dynamic how to delete the dynamic data as well.
this is my discussion forum code
package com.example.pitechnologies.pkguru.fragment;
public class DiscussionForumFragment extends Fragment {
TextView title;
RelativeLayout askquestion;
public View view;
UserProfileData userProfileData;
String U_id;
EditText que, desc;
TextView btnask;
String uname;
LinearLayout linearLayout;
ImageView imgSpoon;
final List<Model_Forum> unilist = new ArrayList<>();
private static String TAG = DiscussionForumFragment.class.getSimpleName();
private RecyclerView forumrecyclerView;
private ForumList_Adapter forumAdapter;
public DiscussionForumFragment() {
}
#Override
public void onStart() {
((AppCompatActivity) getActivity()).getSupportActionBar().hide();
super.onStart();
}
#Override
public void onResume() {
super.onResume();
((AppCompatActivity) getActivity()).getSupportActionBar().hide();
// forumdata();
}
#Override
public void onStop() {
super.onStop();
((AppCompatActivity) getActivity()).getSupportActionBar().show();
}
#Override
public View onCreateView(final LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_discussion_forum, container, false);
title = (TextView) view.findViewById(R.id.forumtitle);
title.setText("DISCUSSION FORUM");
askquestion = (RelativeLayout) view.findViewById(R.id.askquestion);
askquestion.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(PreferenceHelper.getInstance(getActivity()).getSemid() == null) {
Intent intent = new Intent(getActivity(), ActivityLoginSignUp.class);
startActivity(intent);
}else {
Intent intent = new Intent(getActivity(), ActivityQuestionaire.class);
intent.putExtra("uu_id", U_id);
startActivity(intent);
}
}
});
forumrecyclerView = (RecyclerView) view.findViewById(R.id.recyclerview_forum);
forumrecyclerView.setHasFixedSize(true);
forumrecyclerView.setLayoutManager(new LinearLayoutManager(DiscussionForumFragment.this.getActivity()));
forumAdapter = new ForumList_Adapter(DiscussionForumFragment.this.getContext(), unilist);
forumrecyclerView.setAdapter(forumAdapter);
forumrecyclerView.setNestedScrollingEnabled(false);
imgSpoon = (ImageView) view.findViewById(R.id.image_spoon);
linearLayout = (LinearLayout) view.findViewById(R.id.pg_loader);
linearLayout.setVisibility(View.INVISIBLE);
forumdata();
return view;
}
public void forumdata() {
unilist.clear();
/* final ProgressDialog pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Loading...");
pDialog.show();*/
linearLayout.setVisibility(View.VISIBLE);
ObjectAnimator flip = ObjectAnimator.ofFloat(imgSpoon, "rotationY", 0f, 180f);
flip.setDuration(800);
flip.setRepeatCount(Animation.INFINITE);
flip.start();
StringRequest strReq = new StringRequest(Request.Method.POST,
URLconstant.FORUM, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, response.toString());
try {
JSONObject data = new JSONObject(response);
Log.d("data", data.toString());
JSONArray datarray = data.getJSONArray("data");
for (int i = 0; i < datarray.length(); i++) {
JSONObject secondobj = datarray.getJSONObject(i);
Log.d("secondobj", secondobj.toString());
Model_Forum model_forum = new Model_Forum();
model_forum.mforum_id = secondobj.getString("forum_id");
model_forum.mqst = secondobj.getString("qst");
model_forum.mqst_description = secondobj.getString("qst_description");
model_forum.mqst_uid = secondobj.getString("qst_uid");
model_forum.muser_id = secondobj.getString("user_id");
model_forum.mfullname = secondobj.getString("fullname");
model_forum.muniver_id = secondobj.getString("univer_id");
model_forum.mbranchid = secondobj.getString("branchid");
model_forum.msemid = secondobj.getString("semid");
model_forum.mcollegeid = secondobj.getString("collegeid");
model_forum.muser_image = secondobj.getString("user_image");
model_forum.mq_date = secondobj.getString("q_date");
model_forum.mq_time = secondobj.getString("q_time");
unilist.add(model_forum);
}
if (getContext() != null) {
/* forumAdapter = new ForumList_Adapter(DiscussionForumFragment.this.getContext(), unilist);
forumrecyclerView.setAdapter(forumAdapter);*/
forumAdapter.notifyDataSetChanged();
}
} catch (JSONException e) {
e.printStackTrace();
}
// pDialog.dismiss();
linearLayout.setVisibility(View.INVISIBLE);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
// pDialog.dismiss();
linearLayout.setVisibility(View.INVISIBLE);
}
});
MySingleton.getInstance(getActivity()).addToRequestQueue(strReq);
}
I have a videoview and listview/gridview in my playvideo activity.
One video is already playing in the videoview. But now i want to play the other video which are showing in the listview/gridview how can i do that?
Playvideo Activity
public class playvideoactivity extends Activity {
GridViewWithHeaderAndFooter grid;
String videourl="http://www.quirksmode.org/html5/videos/big_buck_bunny.mp4";
private static final String url = "http://dakwf.org/api/bd_english.json";
private List<ChannelItem> chanellist = new ArrayList<ChannelItem>();
private static final String TAG = MainActivity.class.getSimpleName();
public static VideoView player;
public static ImageButton btnPlayPause;
private ImageView btnFullscreen;
private ProgressBar spinner;
private RelativeLayout mediaController;
private Handler btnHandler = new Handler();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
spinner = (ProgressBar) findViewById(R.id.progressBar);
player=(VideoView) findViewById(R.id.player);
mediaController=(RelativeLayout) findViewById(R.id.media_controller);
spinner.setVisibility(View.VISIBLE);
mediaController.setVisibility(View.INVISIBLE);
btnPlayPause=(ImageButton) findViewById(R.id.btn_playpause);
btnFullscreen=(ImageView) findViewById(R.id.btn_fullscreen);
final CustomGridviewadapter customGridview= new CustomGridviewadapter(this,chanellist);
grid = (GridViewWithHeaderAndFooter) findViewById(R.id.grid_view);
setGridViewHeaderAndFooter();
grid.setAdapter(customGridview);
//----------- Creating volley request obj--------------------
JsonArrayRequest movieReq = new JsonArrayRequest(url,new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
ChannelItem item = new ChannelItem();
item.setTitle(obj.getString("title"));
item.setThumbnailUrl(obj.getString("image"));
// adding movie to movies array
chanellist.add(item);
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
customGridview.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(movieReq);
//------------------- Mediacontroller Visiblity-------------------------------------
player.setOnTouchListener(new View.OnTouchListener()
{
public boolean onTouch(final View paramAnonymousView, MotionEvent paramAnonymousMotionEvent)
{
if (paramAnonymousMotionEvent.getAction() == 0){
if (MainActivity.this.mediaController.getVisibility() != View.INVISIBLE) {
}
MainActivity.this.mediaController.setVisibility(View.VISIBLE);
MainActivity.this.btnHandler.postDelayed(new Runnable(){
public void run(){
MainActivity.this.mediaController.setVisibility(View.INVISIBLE);
}
}, 2000L);
}
for (;;){
return true;
}
}
});
//------FullScreen Button -----
btnFullscreen.setOnClickListener(new View.OnClickListener(){
public void onClick(View paramAnonymousView) {
Intent i = new Intent(MainActivity.this, FullScreenView.class);
startActivity(i);
}
});
//------Play Pause Button ----------
btnPlayPause.setOnClickListener(new View.OnClickListener() {
public void onClick(View paramAnonymousView){
if ( (player != null) && (MainActivity.this.player.isPlaying()) ){
MainActivity.this.player.pause();
MainActivity.this.btnPlayPause.setBackgroundResource(R.drawable.btn_play);
return;
}
MainActivity.this.player.start();
MainActivity.this.btnPlayPause.setBackgroundResource(R.drawable.btn_pause);
return;
}
});
//----------------------------------------
try {
MediaController mController = new MediaController(MainActivity.this);
mController.setAnchorView(player);
Uri video = Uri.parse(videourl);
player.setMediaController(mController);
player.setVideoURI(video);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
player.setMediaController(null);
player.requestFocus();
player.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer arg0) {
player.start();
hidespinner();
}
});
}
// ------------ Header Gridview ----------------
#SuppressLint({"InflateParams", "SetTextI18n"})
private void setGridViewHeaderAndFooter() {
LayoutInflater layoutInflater = LayoutInflater.from(this);
View headerView = layoutInflater.inflate(R.layout.grid_header, null, false);
//locate views
TextView headerText = (TextView)headerView.findViewById(R.id.textViewheader);
headerText.setText("Suggestion");
headerView.setOnClickListener(onClickListener(0));
grid.addHeaderView(headerView);
}
private View.OnClickListener onClickListener(final int i) {
return new View.OnClickListener() {
#Override
public void onClick(View v) {
if (i == 0) {
// Toast.makeText(MainActivity.this, "Header Clicked!", Toast.LENGTH_SHORT).show();
} else {
// Toast.makeText(MainActivity.this, "Footer Clicked!", Toast.LENGTH_SHORT).show();
}
}
};
}
#Override
public void onDestroy() {
super.onDestroy();
hidespinner();
}
private void hidespinner() {
if (spinner != null) {
spinner.setVisibility(View.INVISIBLE);
spinner = null;
}
}
}
When opening starting the app you need to get the data and store on a variable or into database.
Create a ChannelList type List (List<ChannelList>) and store ChannelList data into it.
List<ChannelList> list = new ArrayList<>(); // containing all data
You can store Title, VideoUrl, iconUrl and add it to the list.
When clicking on a List Item you will get the position by using setOnItemClickListener.
And then use the position to get the clicked ChannelList position.
Suppose your list type variable is channelList.
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
ChannelList channelList= list.get(position);
// now you have all data of clicked ChannelList
// do whatever you like
//channelList.getVideoUrl(); etc as your getter method
}
}
});
For more about List, you can check it Here