Playing a video in android - java

Im implementing a video playback in android im completely new to android, and this is the bit of code i have gathered so far.
according to the logic it should play a video. don't know where im doing wrong.
package com.themetanoia.readfilefromsdc;
import java.io.File;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.MediaController;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;
import android.widget.AdapterView.OnItemClickListener;
public class ReadFileFromSDCActivity extends ListActivity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Get the file path for external storage
String a = Environment.getExternalStorageDirectory().getAbsolutePath();
final String finalPath = a+"/Videos";
//Define new file function
File f=new File(finalPath);
if(f.isDirectory()){
//Define arrayadapter
setListAdapter(new ArrayAdapter<String>(this, R.layout.listview,files));
//Define listview
ListView listview = getListView();
listview.setTextFilterEnabled(true);
//Onclick list item event
listview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
//get selected items
String selectedValue = (String) getListAdapter().getItem(position);
Uri uri = Uri.parse(finalPath);
MediaController mediaController = new MediaController(getBaseContext());
mediaController.setAnchorView(mVideoView);
Uri video = Uri.parse(finalPath+"/"+selectedValue);
mVideoView.setMediaController(mediaController);
mVideoView.setVideoURI(video);
mVideoView.start();
}
});
}
}
}

<VideoView
android:id="#+id/videoView1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
VideoView vv = (VideoView) findViewById(R.id.videoView1);
uri = "your video uri";
vv.setVideoURI(Uri.parse(uri));
vv.start();
vv.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
finish();
}
});

Related

onclicklistner on videoview in recyclerview

hi i am building a app where, i show videos from firebase to videoview which is in recyclerview in gridlayout form, means at each fragment there are two videos shown, i want to add on clicklisten to them as when someone click on it, a new activity opens and at that activity, the same video is shown in fullscreen (vertically). i used putextra to transfer my data, but i am getting error, "uristring",
bellow is my code
Adapter code
package com.example.godhelpme.Adapter;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.MediaController;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.recyclerview.widget.RecyclerView;
import com.example.godhelpme.Fragments.HomeFragment;
import com.example.godhelpme.FullScreen;
import com.example.godhelpme.LoginActivity;
import com.example.godhelpme.MainActivity;
import com.example.godhelpme.Model.Post;
import com.example.godhelpme.Model.User;
import com.example.godhelpme.R;
import com.example.godhelpme.StartActivity;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.List;
public class PostAdapter extends RecyclerView.Adapter<PostAdapter.ViewHolder>{
private Context mContext;
private List<Post> mPosts;
private FirebaseUser firebaseUser;
public PostAdapter(Context mContext, List<Post> mPosts) {
this.mContext = mContext;
this.mPosts = mPosts;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(mContext).inflate(R.layout.upload_item, parent,false);
return new PostAdapter.ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
Post post = mPosts.get(position);
try {
String link = post.getVideourl();
MediaController mediaController = new MediaController(mContext);
mediaController.setAnchorView(holder.video1);
Uri video = Uri.parse(link);
holder.video1.setMediaController(mediaController);
holder.video1.setVideoURI(video);
holder.video1.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mediaPlayer) {
try {
if (mediaPlayer.isPlaying()) {
mediaPlayer.stop();
mediaPlayer.release();
mediaPlayer = new MediaPlayer();
}
mediaPlayer.setVolume(0f, 0f);
mediaPlayer.setLooping(false);
mediaPlayer.start();
} catch (Exception e) {
e.printStackTrace();
}
mediaController.setVisibility(View.GONE);
}
});
holder.video1.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
mediaPlayer.start(); }
});
holder.id.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent in = new Intent(view.getContext(),FullScreen.class);
in.putExtra(" videourl", post.getVideourl());
in.putExtra("publisher", post.getPublisher());
in.putExtra("postid", post.getPostid());
view.getContext().startActivity(in);
}
});
}catch (Exception e){
Toast.makeText(mContext,e.getMessage(), Toast.LENGTH_SHORT).show();
}
FirebaseDatabase.getInstance().getReference().child("Users").child(post.getPublisher())
.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
User user = snapshot.getValue(User.class);
holder.id.setText(user.getUsername());
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
#Override
public int getItemCount() {
return mPosts.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
public VideoView video1;
public TextView id;
public ViewHolder(#NonNull View itemView) {
super(itemView);
video1 = itemView.findViewById(R.id.video1);
id = itemView.findViewById(R.id.id);
}
}
}
THAT ACTIVITY CODE WHERE I WANT TO SHOW
package com.example.godhelpme;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.widget.MediaController;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;
import com.example.godhelpme.Model.Post;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
public class FullScreen extends AppCompatActivity {
VideoView videoFull;
TextView idFull;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().hide();
setContentView(R.layout.activity_full_screen);
videoFull = findViewById(R.id.videoFull);
idFull = findViewById(R.id.idFull);
Intent in = getIntent();
try{
String ttr = in.getStringExtra("videourl");
MediaController mediaController = new MediaController(this);
mediaController.setAnchorView(videoFull);
Uri video1 = Uri.parse(ttr);
videoFull.setMediaController(mediaController);
videoFull.setVideoURI(video1);
}catch (Exception e){
Toast.makeText(this,e.getMessage(), Toast.LENGTH_SHORT).show();
}
videoFull.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
mediaPlayer.start(); }
});
idFull.setText(in.getStringExtra("publisher"));
}
}
PLEASE HELP GUYS PLEASE
It took me three days to figure out what's the problem in my code. After knowing my mistake i am feeling very ashamed as well as happy that i figured, it out.
the mistake is in the adapter code,
in.putExtra(" videourl", post.getVideourl());
String ttr = in.getStringExtra("videourl");
the difference between above two code line is the, in first line there is space before the videourl and in the second line there is no space before videourl, and that's a problem. :-)

how can I let the array list to be clickable?

I am trying to handle this list to be clickable.
When I set an intent activity it doesn't work so how can I handle each element in this array list.
The error is when I press on any element in this array list it left me to the last intent I gave it.
package com.adnan.android.autofix;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.view.menu.MenuView;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.TextView;
import java.net.Inet4Address;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity implements {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Array list content
ArrayList<String> CarsBrand = new ArrayList<String>();
CarsBrand.add("Alfa Romeo");
CarsBrand.add("Audi");
CarsBrand.add("BMW");
CarsBrand.add("Brilliance");
CarsBrand.add("BYD");
CarsBrand.add("Changan");
CarsBrand.add("Chery");
CarsBrand.add("Chevorlet");
CarsBrand.add("Chrysler");
ArrayAdapter<String> CarsBrandAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, CarsBrand);
GridView listView = (GridView) findViewById(R.id.ListCarsBrands);
listView.setAdapter(CarsBrandAdapter);
// handling the array list
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent AlfaRomeoIntent = new Intent(MainActivity.this, AlfaRomeo.class);
startActivity(AlfaRomeoIntent);
Intent AudiIntent = new Intent(MainActivity.this, com.adnan.android.autofix.Audi.class);
startActivity(AudiIntent);
}
});
}
}
Maybe you can map your list items to their corresponding activity classes like this:
package com.adnan.android.autofix;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.view.menu.MenuView;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.TextView;
import java.net.Inet4Address;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity implements {
HashMap<String, Class> intentMap ;
ArrayList<String> CarsBrand;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Array list content
CarsBrand = new ArrayList<String>();
CarsBrand.add("Alfa Romeo");
CarsBrand.add("Audi");
CarsBrand.add("BMW");
CarsBrand.add("Brilliance");
CarsBrand.add("BYD");
CarsBrand.add("Changan");
CarsBrand.add("Chery");
CarsBrand.add("Chevorlet");
CarsBrand.add("Chrysler");
ArrayAdapter<String> CarsBrandAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, CarsBrand);
intentMap = new HashMap<String, Class>()
{{
put("Alfa Romeo", AlfaRomeo.class);
put("Audi", Audi.class);
// PUT ALL STRING-CLASS PAIRS LIKE THIS
}};
GridView listView = (GridView) findViewById(R.id.ListCarsBrands);
listView.setAdapter(CarsBrandAdapter);
// handling the array list
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Class selectedIntentClass = intentMap.get(CarsBrand.get(position));
Intent intent = new Intent(MainActivity.this, selectedIntentClass);
startActivity(intent);
}
});
}
}
You Can Try Like this :
package com.adnan.android.autofix;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.view.menu.MenuView;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.TextView;
import java.net.Inet4Address;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity implements {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Array list content
ArrayList<String> CarsBrand = new ArrayList<String>();
CarsBrand.add("Alfa Romeo");
CarsBrand.add("Audi");
CarsBrand.add("BMW");
CarsBrand.add("Brilliance");
CarsBrand.add("BYD");
CarsBrand.add("Changan");
CarsBrand.add("Chery");
CarsBrand.add("Chevorlet");
CarsBrand.add("Chrysler");
ArrayAdapter<String> CarsBrandAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, CarsBrand);
GridView listView = (GridView) findViewById(R.id.ListCarsBrands);
listView.setAdapter(CarsBrandAdapter);
// handling the array list
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
final String item = (String)parent.getItemAtPosition(position);
switch (item) {
case "Alfa Romeo":
Intent AlfaRomeoIntent = new Intent(MainActivity.this, AlfaRomeo.class);
startActivity(AlfaRomeoIntent);
break;
case "Audi":
Intent AudiIntent = new Intent(MainActivity.this, com.adnan.android.autofix.Audi.class);
startActivity(AudiIntent);
break;
}
}
});
}
}

How to set text from listview Android-Studio

I am making an album music application on Android Studio with ListView. now I want to make music notifications that are being played using textview. if the item in the listview is clicked, then the textview will change as written in the listview. can anyone help me? Here my code. Thanks for your attention. :)
import android.content.pm.ActivityInfo;
import android.media.MediaPlayer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import com.google.android.gms.ads.AdRequest;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.InterstitialAd;
import com.google.android.gms.ads.MobileAds;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class Main2Activity extends AppCompatActivity implements
AdapterView.OnItemClickListener {
ListView songListView;
MediaPlayer player;
int[] IMAGES = {R.drawable.adzan_mp3_offline_1, R.drawable.adzan_mp3_offline_4};
String[] songs = {"song 1","song 2"};
int[] ids={R.raw.adzan_mp3_offline_turkey_a,R.raw.adzan_mp3_offline_turkey_b};
private AdView mAdview;
private InterstitialAd mInterstitialAd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
songListView = findViewById(R.id.list);
ArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1,songs);
songListView.setAdapter(adapter);
songListView.setOnItemClickListener(this);
}
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
if (player!=null && player.isPlaying())
player.stop();
player=MediaPlayer.create(this,ids[i]);
player.start();
}
#Override
public void onBackPressed ()
{
if (player != null)
player.stop();
super.onBackPressed();
}
#Override
public void onPause ()
{
if (player != null)
{
player.pause();
player.stop();
}
super.onPause();
}
}
To get the text of the clicked listener use this
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
String currentText = parent.getItemAtPosition(position); // Assuming you've used only string
}
Another way to get the item clicked is to pass the position to Adapter and get the selected object from Adapter. Then you can use the selected object in any way you like.
Hope it helps

Unable to load data in Webview or Webview is blank when clicking on listitem

This is my webview actvity:
package com.example.murarilal.volley;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class ArticleActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_article);
WebView webView=(WebView)findViewById(R.id.webView);
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebViewClient(new WebViewClient());
Intent intent=getIntent();
webView.loadData(intent.getStringExtra("description"),"text/html","UTF-8");
}
}
Mainactivity:
When I click on a listitem then in new activity webview appears blank. Nothing is there in the webview "https://newsapi.org/v1/articles?source=techcrunch&apiKey=59b308aec9f242fe98b527ab9ba93199" this is the URL. The same problem appears when I tested it on real device.
package com.example.murarilal.volley;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
public class MainActivity extends AppCompatActivity {
RequestQueue queue;
ListView listView;
List<Hero> heroList;
private String url="https://newsapi.org/v1/articles?source=techcrunch&apiKey=59b308aec9f242fe98b527ab9ba93199";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
queue = Volley.newRequestQueue(this);
home();
listView = (ListView) findViewById(R.id.listView);
heroList = new ArrayList<>();
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Intent intent = new Intent(getApplicationContext(),ArticleActivity.class);
startActivity(intent);
}
});
}
public void home() {
JsonObjectRequest request =new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONObject obj = new JSONObject(String.valueOf(response));
JSONArray array = obj.getJSONArray("articles");
for (int i = 0; i < array.length(); i++) {
Hero hero = new Hero((String) array.getJSONObject(i).get("title"), (String) array.getJSONObject(i).get("urlToImage"));
heroList.add(hero);
}
ListViewAdapter adapter = new ListViewAdapter(heroList, getApplicationContext());
listView.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
queue.add(request);
}
}
This is my mainactvity.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.murarilal.volley.MainActivity">
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/listView"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
/>
</RelativeLayout>
You are fetching data from intent.getStringExtra("description") but you didn't add data into Intent which you want to pass, Try this,
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Intent intent=new Intent(getApplicationContext(),ArticleActivity.class);
intent.putExtra("description","whatever data you want to pass");
startActivity(intent);
}
});
And load your URL in below way,
WebView myWebView = (WebView) findViewById(R.id.webview);
myWebView.loadUrl("http://www.example.com");
Load an URL in webview:
private String url="https://newsapi.org/v1/articles?source=techcrunch&apiKey=59b308aec9f242fe98b527ab9ba93199";
WebView webView=(WebView)findViewById(R.id.webView);
webView.loadurl(url);
https://developer.android.com/reference/android/webkit/WebView.html#loadUrl(java.lang.String)

How to use viewHolder pattern to keep UI elements on scroll in listView?

I am looking into using the viewHolder pattern for making my UI elements not get reset to the default when my listview is scrolled. After looking into it Im not sure how to go about this. Im not even sure if my existing code will even allow me to use viewHolder pattern. I am a beginner so please elaborate and do not skip the details. Thank you
MainActivity.java
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.app.Activity;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewSwitcher;
import java.util.ArrayList;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ArrayList<String> Chores = new ArrayList<>();
Chores.add("");
final ListAdapter MyAdapter = new CustomAdapter(this, Chores);
ListView listViewObject = (ListView)findViewById(R.id.customListView_ID);
listViewObject.setAdapter(MyAdapter);
listViewObject.setOnItemClickListener(
new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id){
String ChoreString = String.valueOf(parent.getItemAtPosition(position));
}
}
);
final Button button = (Button) findViewById(R.id.button_ID);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Chores.add("");
((ArrayAdapter)MyAdapter).notifyDataSetChanged();
}
});
}
}
CustomAdapter.java
import android.content.Context;
import android.content.DialogInterface;
import android.support.annotation.NonNull;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
import static com.example.emilythacker.chorelist.R.id.textView_ID;
class CustomAdapter extends ArrayAdapter{
public CustomAdapter(Context context, ArrayList choreText) {
super(context, R.layout.custon_listview_row, choreText);
}
#NonNull
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater myInflater = LayoutInflater.from(getContext());
View customView = myInflater.inflate(R.layout.custon_listview_row, parent, false);
ImageButton imageButton = (ImageButton) customView.findViewById(R.id.imageButton_ID);
final TextView textView = (TextView) customView.findViewById(textView_ID);
textView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//what happens when textView is clicked
AlertDialog alertDialog = new AlertDialog.Builder(getContext()).create();
final EditText input = new EditText(getContext());
input.setHint("hint");
alertDialog.setView(input);
alertDialog.setTitle("Set Chore");
alertDialog.setMessage("Alert message to be shown");
alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
//this will set text to "hello" only if user does not enter anything into input
//textView.setText("hello");
//this also will only work if there is no input entered into input...wich will change textView into empty space
textView.setText(input.getText().toString());
//works the same with or without dialog.dismiss();
dialog.dismiss();
}
});
alertDialog.show();
}
});
imageButton.setImageResource(R.drawable.clock);
return customView;
}
}
I found this tutorial really helpful when learning to use the ViewHolder Pattern. It is pretty clear in explaining how to use it, but feel free to ask if you feel stuck.
When you are performing some change to any list Item we should call notifyDataSetChanged(),so that the listview gets updated.
Answer to your question:
call notifyDataSetChanged() in textview.onClickListener() method after updating the text.
Better to shift to RecyclerView, In this when we add new item we can just call notifyItemAdded(position) which will refresh only the view at that position but not the whole.
And when we update any item we can call notifyItemChanged(position).

Categories