I want EditText become AutoComplete when user start typing in the EditText field. I have create this code
public class PegawaiFragment extends Fragment {
public static PegawaiFragment newInstance() {
PegawaiFragment fragment = new PegawaiFragment();
return fragment;
}
String namapegawai;
AutoCompleteTextView textAutoComplete;
ListView StudentListView;
ProgressBar progressBar;
String HttpUrl = "http://192.168.43.241/Android/MyKoperasi/PegawaiDashboard.php";
List<String> IdList = new ArrayList<>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_pegawai, container, false);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
namapegawai = prefs.getString(MainActivity.UserName,MainActivity.UserName);
TextView NamaPegawai = v.findViewById(R.id.TextViewNamaPegawai);
NamaPegawai.setText(namapegawai);
textAutoComplete = v.findViewById(R.id.autoCompleteTextView1);
ArrayAdapter adapter = new ArrayAdapter(getActivity(),android.R.layout.simple_list_item_1);
textAutoComplete.setAdapter(adapter);
textAutoComplete.setThreshold(1);
StudentListView = v.findViewById(R.id.listview2);
progressBar = v.findViewById(R.id.progressBar1);
new GetHttpResponse(getActivity()).execute();
//Adding ListView Item click Listener.
StudentListView.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// TODO Auto-generated method stub
//Intent intentSemuaMemberLihat = new Intent(getActivity(),SemuaMemberLihat.class);
// Sending ListView clicked value using intent.
//intentSemuaMemberLihat.putExtra("ListViewValue", IdList.get(position).toString());
//startActivity(intentSemuaMemberLihat);
}
});
return v;
}
// JSON parse class started from here.
class GetHttpResponse extends AsyncTask<Void, Void, Void>
{
public Context context;
String JSonResult;
List<Member> studentList;
public GetHttpResponse(Context context)
{
this.context = context;
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0)
{
// Passing HTTP URL to HttpServicesClass Class.
HttpServicesClass httpServicesClass = new HttpServicesClass(HttpUrl);
try
{
httpServicesClass.ExecutePostRequest();
if(httpServicesClass.getResponseCode() == 200)
{
JSonResult = httpServicesClass.getResponse();
if(JSonResult != null)
{
JSONArray jsonArray = null;
try {
jsonArray = new JSONArray(JSonResult);
JSONObject jsonObject;
Member member;
studentList = new ArrayList<Member>();
for(int i=0; i<jsonArray.length(); i++)
{
member = new Member();
jsonObject = jsonArray.getJSONObject(i);
// Adding Student Id TO IdList Array.
IdList.add(jsonObject.getString("id").toString());
//Adding Student Name.
member.nama = jsonObject.getString("nama").toString();
//member.nrp = jsonObject.getString("nrp").toString();
studentList.add(member);
}
}
catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
else
{
Toast.makeText(context, httpServicesClass.getErrorMessage(), Toast.LENGTH_SHORT).show();
}
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result)
{
progressBar.setVisibility(View.GONE);
StudentListView.setVisibility(View.VISIBLE);
if(studentList != null) {
ListAdapterClass adapter = new ListAdapterClass(studentList, context);
StudentListView.setAdapter(adapter);
}else
{
Toast.makeText(context, "Tidak ada data ditampilkan", Toast.LENGTH_SHORT).show();
}
}
}
}
This code shows perfect, but when I start typing in EditText which in autoCompleteTextView1, no suggestion name come out. I think this is in here
textAutoComplete = v.findViewById(R.id.autoCompleteTextView1);
ArrayAdapter adapter = new ArrayAdapter(getActivity(),android.R.layout.simple_list_item_1);
textAutoComplete.setAdapter(adapter);
textAutoComplete.setThreshold(1);
But why the EditText doesn't show the suggestions? instead, my ListView works perfect there.
Here is my XML code
<FrameLayout 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"
tools:context="com.network.poeja.mykoperasi.PegawaiFragment">
<TextView
android:id="#+id/TextViewNamaPegawai"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<AutoCompleteTextView
android:layout_weight="1"
android:id="#+id/autoCompleteTextView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="Text Auto Complete"
android:layout_below="#+id/TextViewNamaPegawai">
<requestFocus />
</AutoCompleteTextView>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="50dp"
android:layout_below="#+id/autoCompleteTextView1">
<!-- TODO: Update blank fragment layout -->
<ListView
android:id="#+id/listview2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:layout_below="#+id/logos"
android:layout_centerHorizontal="true"
android:layout_marginTop="50dip"/>
<ProgressBar
android:id="#+id/progressBar1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:visibility="visible" />
</RelativeLayout>
</FrameLayout>
===============ADAPTER CLASS
public class ListAdapterClass extends BaseAdapter {
Context context;
List<Member> valueList;
public ListAdapterClass(List<Member> listValue, Context context)
{
this.context = context;
this.valueList = listValue;
}
#Override
public int getCount()
{
return this.valueList.size();
}
#Override
public Object getItem(int position)
{
return this.valueList.get(position);
}
#Override
public long getItemId(int position)
{
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
ViewItem viewItem = null;
if(convertView == null)
{
viewItem = new ViewItem();
LayoutInflater layoutInfiater = (LayoutInflater)this.context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = layoutInfiater.inflate(R.layout.listview_item, null);
viewItem.TextViewNama = convertView.findViewById(R.id.textViewNama);
viewItem.TextViewNrp = convertView.findViewById(R.id.textViewNrp);
convertView.setTag(viewItem);
}
else
{
viewItem = (ViewItem) convertView.getTag();
}
viewItem.TextViewNama.setText(valueList.get(position).nama);
viewItem.TextViewNrp.setText(valueList.get(position).nrp);
return convertView;
}
}
class ViewItem
{
TextView TextViewNama, TextViewNrp;
}
You need to provide Array containing data on ArrayAdapter. Its the source of data where adapter will search. Here is an example how to use ArrayAdapter and AutoCompleteTextView -
public class MainActivity extends Activity {
String[] data = {"Apple", "Banana", "Cherry", "Date", "Grape", "Kiwi", "Mango", "Pear"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Creating the instance of ArrayAdapter containing list of fruit names
ArrayAdapter<String> adapter = new ArrayAdapter<String>
(this, android.R.layout.simple_list_item_1, data);
//Getting the instance of AutoCompleteTextView
AutoCompleteTextView actv = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView);
actv.setThreshold(1);//will start working from first character
actv.setAdapter(adapter);//setting the adapter data into the AutoCompleteTextView
actv.setTextColor(Color.RED);
}
}
Based on your code of AutoCompleteTextView. I made a solution.
String[] data = {"Apple", "Banana", "Cherry", "Date", "Grape", "Kiwi", "Mango", "Pear"};
GetHttpResponse getHttpResponse = new GetHttpResponse(getActivity());
getHttpResponse.execute();
textAutoComplete = v.findViewById(R.id.autoCompleteTextView1);
List<Member> studentList = getHttpResponse.getStudentList();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, studentList.toArray(new String[studentList.size()]));
textAutoComplete.setAdapter(adapter);
textAutoComplete.setThreshold(1);
Add a method to get studentList from GetHttpResponse class -
// JSON parse class started from here.
class GetHttpResponse extends AsyncTask<Void, Void, Void>
{
public Context context;
String JSonResult;
List<Member> studentList;
public GetHttpResponse(Context context)
{
this.context = context;
}
public ArrayList<Member> getStudentList(){
return this.studentList;
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0)
{
// Passing HTTP URL to HttpServicesClass Class.
HttpServicesClass httpServicesClass = new HttpServicesClass(HttpUrl);
try
{
httpServicesClass.ExecutePostRequest();
if(httpServicesClass.getResponseCode() == 200)
{
JSonResult = httpServicesClass.getResponse();
if(JSonResult != null)
{
JSONArray jsonArray = null;
try {
jsonArray = new JSONArray(JSonResult);
JSONObject jsonObject;
Member member;
studentList = new ArrayList<Member>();
for(int i=0; i<jsonArray.length(); i++)
{
member = new Member();
jsonObject = jsonArray.getJSONObject(i);
// Adding Student Id TO IdList Array.
IdList.add(jsonObject.getString("id").toString());
//Adding Student Name.
member.nama = jsonObject.getString("nama").toString();
//member.nrp = jsonObject.getString("nrp").toString();
studentList.add(member);
}
}
catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
else
{
Toast.makeText(context, httpServicesClass.getErrorMessage(), Toast.LENGTH_SHORT).show();
}
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result)
{
progressBar.setVisibility(View.GONE);
StudentListView.setVisibility(View.VISIBLE);
if(studentList != null) {
ListAdapterClass adapter = new ListAdapterClass(studentList, context);
StudentListView.setAdapter(adapter);
}else
{
Toast.makeText(context, "Tidak ada data ditampilkan", Toast.LENGTH_SHORT).show();
}
}
}
Related
I am working on listview example, I want tid from mysql database onclick selected listview .how to do it please help me , I am working from long time on that but can not found any solution.
ListTask Activity
public class ListTask extends Activity {
Task task_;
ListView listCollege;
ProgressBar proCollageList;
TextView GetTaskName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_task);
listCollege = (ListView)findViewById(R.id.tasklist);
proCollageList = (ProgressBar)findViewById(R.id.proCollageList);
GetTaskName = (TextView) findViewById(R.id.taskname);
new GetHttpResponse(this).execute();
}
private class GetHttpResponse extends AsyncTask<Void, Void, Void>
{
private Context context;
String result;
List<Task> Task_;
public GetHttpResponse(Context context)
{
this.context = context;
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0)
{
HttpService httpService = new HttpService("http://192.168.0.103/GroupBuilder/GetListTask.php");
try
{
httpService.ExecutePostRequest();
if(httpService.getResponseCode() == 200)
{
result = httpService.getResponse();
System.out.println("Result . . . "+result);
Log.d("Result", result);
if(result != null)
{
JSONArray jsonArray = null;
try {
jsonArray = new JSONArray(result);
JSONObject object;
JSONArray array;
// cources college;
Task_ = new ArrayList<Task>();
for(int i=0; i<jsonArray.length(); i++)
{
task_ = new Task();
object = jsonArray.getJSONObject(i);
task_.taskname = object.getString("taskname");
task_.tid = object.getString("tid");
System.out.println("Taask Tid "+task_.tid);
Task_.add(task_);
}
}
catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
else
{
Toast.makeText(context, httpService.getErrorMessage(), Toast.LENGTH_SHORT).show();
}
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
ListAdapter class
public class ListTaskAdapter extends BaseAdapter {
Context context;
List<Task> taskList;
Task task_;
public ListTaskAdapter(List<Task> listValue, Context context)
{
this.context = context;
this.taskList = listValue;
}
#Override
public int getCount() {
return this.taskList.size();
}
#Override
public Object getItem(int position) {
return this.taskList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, final ViewGroup viewGroup) {
ViewTaskName viewtaskname = null;
if(convertView == null)
{
viewtaskname = new ViewTaskName();
LayoutInflater layoutInfiater = (LayoutInflater)this.context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
//LayoutInflater layoutInfiater = LayoutInflater.from(context);
convertView = layoutInfiater.inflate(R.layout.listtaskadapter, null);
viewtaskname.task_name = (TextView)convertView.findViewById(R.id.taskname);
final String str = viewtaskname.task_name.getText().toString();
convertView.setTag(viewtaskname);
}
else
{
viewtaskname = (ViewTaskName) convertView.getTag();
}
viewtaskname.task_name.setText(taskList.get(position).taskname);
return convertView;
}
}
class ViewTaskName
{
TextView task_name;
}
class Task{
public String taskname;
public String tid;
}
activity_list_task.xml code
<ListView
android:id="#+id/tasklist"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:visibility="visible"
android:background="#38a2ed"
android:layout_marginTop="35dp" >
</ListView>
listadaper code
<TextView
android:id="#+id/taskname"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:text="TaskName"
android:textColor="#000000"
android:textSize="18sp"
/>
I am not getting any solution please help me and update my code , Thanks
You should use setOnItemClickListener
Register a callback to be invoked when an item in this AdapterView has
been clicked.
Create a TextView which hold ID like Name .
<TextView
android:id="#+id/taskID"
android:layout_width="0dp"
android:layout_height="0dp"
/>
Then
listCollege.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view,int position, long id)
{
TextView taskIDOBJ=(TextView)view.findViewById(R.id.taskID);
String item = tasknameOBJ.getText().toString();
Toast.makeText(this,"You selected : " + item,Toast.LENGTH_SHORT).show();
}
});
Simple way
String str_ID = Task_.get(position).tid;
Code
listCollege.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view,int position, long id)
{
String str_ID = Task_.get(position).tid;
Toast.makeText(this,"You selected : " + str_ID ,Toast.LENGTH_SHORT).show();
}
});
try this
//declare global use this array list in AsyncTask response to add
List<Tast> taskList = new ArrayList<>();
listCollege.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String tid = taskList.get(position).tid;
}
});
use setOnItemClickListener method and get id from sqllite , this method gives you a position , on the bases of position you got your id from bean class . follow this link .
Get Id from database in a listview onclick
view.setTag(id);
view.getTag();
I am using a list view in fragment which loads data using json in that i cannot able to view the list view.In the sched it shows the constructor is never used i don't know where i have done wrong in the code.The server part works fine.
Fragment:
public class SchedulessFragment extends Fragment{
private static final String TAG = MatAct.class.getSimpleName();
private static final String url = "http://nammakovai2015-001-site1.1tempurl.com/iplspin/schedules.php";
ProgressDialog pDialog;
List<Sched> movieList = new ArrayList<Sched>();
ListView listview;
CustomListAdapter adapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.schedule_frag, container, false);
adapter = new CustomListAdapter(getActivity(), movieList);
listview = (ListView) v.findViewById(R.id.listView1);
listview.setAdapter(adapter);
// TextView tv = (TextView) v.findViewById(R.id.tvfrag);
// tv.setText(getArguments().getString("msg"));
// tv.setText("Hello");
pDialog = new ProgressDialog(getActivity());
// Showing progress dialog before making http request
pDialog.setMessage("Loading...");
pDialog.show();
// changing action bar color
// Creating volley request obj
JsonArrayRequest movieReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Sched m = new Sched();
m.setTeama(obj.getString("teama"));
m.setTeamb(obj.getString("teamb"));
m.setTdate(obj.getString("tdate"));
m.setTtime(obj.getString("ttime"));
m.setThumbnailUrl(obj.getString("thumbnailUrl"));
m.setTeambthumbnailUrl(obj.getString("teambthumbnailUrl"));
m.setVenue(obj.getString("venue"));
// adding movie to movies array
movieList.add(m);
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(movieReq);
return v;
}
#Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
public static SchedulessFragment newInstance(String text) {
SchedulessFragment f = new SchedulessFragment();
Bundle b = new Bundle();
b.putString("msg", text);
f.setArguments(b);
return f;
}}
ListAdapter:
public class CustomListAdapter extends BaseAdapter{
private Activity activity;
private LayoutInflater inflater;
List<Sched> movieItems;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
public CustomListAdapter(Activity activity, List<Sched> movieItems) {
this.activity = activity;
this.movieItems = movieItems;
}
#Override
public int getCount() {
return movieItems.size();
}
#Override
public Object getItem(int location) {
return movieItems.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.listitem_ros, null);
if (imageLoader == null)
imageLoader = AppController.getInstance().getImageLoader();
NetworkImageView thumbNail = (NetworkImageView) convertView
.findViewById(R.id.pict);
NetworkImageView teambthumbnail=(NetworkImageView) convertView.findViewById(R.id.pict1);
TextView teama = (TextView) convertView.findViewById(R.id.scheduleteama_name);
TextView teamb = (TextView) convertView.findViewById(R.id.schduleteamb_name);
TextView tdate = (TextView) convertView.findViewById(R.id.datess);
TextView ttime = (TextView) convertView.findViewById(R.id.timess);
TextView venue=(TextView)convertView.findViewById(R.id.schedulevenue);
// getting movie data for the row
Sched m = movieItems.get(position);
// thumbnail image
thumbNail.setImageUrl(m.getThumbnailUrl(), imageLoader);
teambthumbnail.setImageUrl(m.getTeambthumbnailUrl(),imageLoader);
// title
teama.setText(m.getTeama());
teamb.setText(m.getTeamb());
tdate.setText(m.getTdate());
ttime.setText(m.getTtime());
venue.setText(m.getVenue());
return convertView;
}}
Sched:
public class Sched {
private String teama,teamb,tdate,ttime,thumbnailUrl,teambthumbnailUrl,venue;
public Sched(){}
public Sched(String teama, String teamb, String tdate, String ttime, String thumbnailUrl, String teambthumbnailurl, String venue)
{
this.teama=teama;
this.teamb=teamb;
this.tdate=tdate;
this.ttime=ttime;
this.thumbnailUrl=thumbnailUrl;
this.teambthumbnailUrl=teambthumbnailurl;
this.venue=venue;
}
public String getTeama(){
return teama;
}
public void setTeama(String teama){
this.teama=teama;
}
public String getTeamb(){
return teamb;
}
public void setTeamb(String teamb){
this.teamb=teamb;
}
public String getTdate(){
return tdate;
}
public void setTdate(String tdate){
this.tdate=tdate;
}
public String getTtime(){
return ttime;
}
public void setTtime(String ttime){
this.ttime=ttime;
}
public String getThumbnailUrl() {
return thumbnailUrl;
}
public void setThumbnailUrl(String thumbnailUrl) {
this.thumbnailUrl = thumbnailUrl;
}
public String getTeambthumbnailUrl() {
return teambthumbnailUrl;
}
public void setTeambthumbnailUrl(String teambthumbnailUrl){
this.teambthumbnailUrl=teambthumbnailUrl;
}
public String getVenue(){
return venue;
}
public void setVenue(String venue){
this.venue=venue;
}}
xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<ListView
android:id="#+id/listView1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:dividerHeight="1dp"
>
</ListView>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:id="#+id/tvfrag"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="219dp" />
Your problem is that you are creating the adapter before the movieList has been populated. Move these two lines:
adapter = new CustomListAdapter(getActivity(), movieList);
listview.setAdapter(adapter);
after the for loop in which you're adding the Movies to the list:
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Sched m = new Sched();
m.setTeama(obj.getString("teama"));
m.setTeamb(obj.getString("teamb"));
m.setTdate(obj.getString("tdate"));
m.setTtime(obj.getString("ttime"));
m.setThumbnailUrl(obj.getString("thumbnailUrl"));
m.setTeambthumbnailUrl(obj.getString("teambthumbnailUrl"));
m.setVenue(obj.getString("venue"));
// adding movie to movies array
movieList.add(m);
} catch (JSONException e) {
e.printStackTrace();
}
//PUT THOSE TWO LINES HERE
Assuming your Request is good and it returns a non-empty JSONArray, this should work.
I'm new in recycle view. Tthis is sample code for my RecycerView. I'm getting data from internet and in onPostExecute() I set the adapter.
RecyclerView recycle;
MyAdapter adapters;
private static String url;
private static final String TAG_CONTACTS = "contacts";
JSONArray contacts = null;
ProgressDialog pDialog;
private int preLast;
int page = 0, in, to;
Boolean loadmore = true;
HashMap<String, String> item;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
url = "http://192.168.1.20/adres/getAds.php";
recycle = (RecyclerView) findViewById(R.id.recycle);
recycle.setItemAnimator(new DefaultItemAnimator());
new GetContacts().execute();
final GestureDetector mGestureDetector = new GestureDetector(MainActivity.this, new GestureDetector.SimpleOnGestureListener() {
#Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
});
}
private class GetContacts extends AsyncTask<Void, Void, ArrayList<HashMap<String, String>>> {
Boolean goterr = false;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected ArrayList<HashMap<String, String>> doInBackground(Void... arg0) {
String jsonStr = Fun.getHtml(url);
Log.v("this", jsonStr);
ArrayList<HashMap<String, String>> dataC = new ArrayList<HashMap<String, String>>();
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
contacts = jsonObj.getJSONArray(TAG_CONTACTS);
if (contacts.length() < 20)
loadmore = false;
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
HashMap<String, String> contact = new HashMap<String, String>();
contact.put("id", new String(c.getString("id").getBytes("ISO-8859-1"), "UTF-8"));
contact.put("name", new String(c.getString("name").getBytes("ISO-8859-1"), "UTF-8"));
dataC.add(contact);
dataC.add(contact);
}
} catch (JSONException e) {
Log.v("this", e.getMessage());
goterr = true;
} catch (UnsupportedEncodingException e) {
Log.v("this", e.getMessage());
goterr = true;
}
} else {
goterr = true;
}
return dataC;
}
#Override
protected void onPostExecute(ArrayList<HashMap<String, String>> result) {
super.onPostExecute(result);
if (pDialog.isShowing() && pDialog != null)
pDialog.dismiss();
if (!isCancelled() && goterr == false && result != null) {
if (adapters == null) {
adapters = new MyAdapter(MainActivity.this, result);
recycle.setAdapter(adapters);
recycle.setLayoutManager(new LinearLayoutManager(MainActivity.this));
} else {
adapters.addAll(result);
}
} else {
//MyToast.makeText(MainActivity.this, DariGlyphUtils.reshapeText(MainActivity.this.getResources().getString(R.string.problemload)));
}
}
}
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
private LayoutInflater inflater;
public ArrayList<HashMap<String, String>> list;
public MyAdapter(Context context, ArrayList<HashMap<String, String>> list) {
inflater = LayoutInflater.from(context);
this.list = list;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parrent, int i) {
View view = inflater.inflate(R.layout.customrow, parrent, false);
MyViewHolder holder = new MyViewHolder(view);
return holder;
}
public void addAll(ArrayList<HashMap<String, String>> result) {
if (this.list == null) {
this.list = result;
} else {
this.list.addAll(result);
}
notifyDataSetChanged();
}
public HashMap<String, String> geting(int position) {
return list.get(position);
}
#Override
public void onBindViewHolder(MyViewHolder viewHolder, int position) {
item = list.get(position);
viewHolder.txt.setText(item.get("onvan"));
}
#Override
public int getItemCount() {
return list.size();
}
class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView txt;
ImageView img;
public MyViewHolder(View itemView) {
super(itemView);
itemView.setOnClickListener(this);
txt = (TextView) itemView.findViewById(R.id.txt);
img = (ImageView) itemView.findViewById(R.id.img);
}
#Override
public void onClick(View v) {
item = adapters.geting(getPosition());
Log.v("this", "id " + item.get("id"));
/*Intent in=new Intent (FistActiivty.this,AdDetails.class);
in.putExtra("ad_id",item.get("id"));
startActivity(in)*/
;
}
}
}
after I run it , I get this error :
RecyclerView﹕ No adapter attached; skipping layout
what is wrong with this code ?
The problem is that during the first layout pass, while your AsyncTask is still fetching data from the network, your RecyclerView has not adapter.
You can instead attach the (empty) adapter in onCreate() and update the adapter's data in your onPostExecute(). Just make sure that your adapter properly handles having an empty data set.
I have a A data stored in ArrayList< HashMap< String, String> > retrieved from JSON
in the form (i.e.)
[{price: =1685 name: =Monographie Der Gattung Pezomachus (Grv.) by Arnold F. Rster}]
And I need to show the all map elements into list form in Android.
I've tried many ways but I'm unable to do it .
Also help me to know about the layouts to use in it
EDITED:
MySimpleArrayAdapter adapter = new MySimpleArrayAdapter(myarr_list);
setListAdapter(adapter);
And in the MySimpleArrayAdapter Class, in Constructor
public MySimpleArrayAdapter( ArrayList<HashMap<String,String>> pl) {
LayoutInflator inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
The control does not proceed after this,
MySimpleArrayAdapter Class
public class MySimpleArrayAdapter extends BaseAdapter{
ArrayList<HashMap<String, String>> ProductList = new ArrayList<HashMap<String, String>>();
LayoutInflater inflater;
#Override
public int getCount() {
// TODO Auto-generated method stub
return 0;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
//Constructor
public MySimpleArrayAdapter( ArrayList<HashMap<String,String>> pl) {
this.ProductList = pl;
inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public View getView(int position, View convertView, ViewGroup parent) {
View myview = convertView;
if (convertView == null) {
myview = inflater.inflate(R.layout.show_search_result, null);
}
TextView price = (TextView) myview.findViewById(R.id.price);
TextView name = (TextView) myview.findViewById(R.id.name);
HashMap<String, String> pl = new HashMap<String, String>();
pl = ProductList.get(position);
//Setting
price.setText(pl.get("price"));
name.setText(pl.get("name"));
return myview;
}
}
I am editing here a onPostExecute class from SearchResultsTask extended by AsyncTask
protected void onPostExecute(JSONObject json) {
if (json != null && json.length() > 0) {
try {
JSONArray json_results = (JSONArray)(json.get("results"));
String parsedResult = "";
System.out.println("-> Size ="+ json_results.length());
for(int i = 0; i < json_results.length(); i++){
HashMap<String, String> map = new HashMap<String, String>();
JSONObject json_i = json_results.getJSONObject(i);
map.put("name: ",json_i.getString("name") + "\n");
map.put("price: ",json_i.getString("price") + "\n");
arr_list.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
System.out.println("-> Size =====arr_llist ="+ arr_list.size());
// CustomListAdapter adapter = new CustomListAdapter (arr_list);
//final StableArrayAdapter adapter = new StableArrayAdapter(this, R.id.result, arr_list);
// listview.setAdapter(adapter);
MyListActivity obj1 = new MyListActivity();
Bundle icicle = null;
obj1.onCreate(icicle);
}
public class MyListActivity extends Activity {
public void onCreate(Bundle icicle) {
// System.out.println("In my list Activity");
// super.onCreate(icicle);
//populate list
MySimpleArrayAdapter adapter = new MySimpleArrayAdapter(this,arr_list);
// System.out.println("in 2");
adapter.getView(0, listview, listview);
listview.setAdapter(adapter);
}
}
#Override
public int getCount() {
return ProductList.size() ;
}
//Constructor
public MySimpleArrayAdapter( ArrayList<HashMap<String,String>> pl, Context c) {
this.ProductList = pl;
inflater = (LayoutInflater)c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
getSystemService() is method of context, you are calling it on instance of adapter.
I want to delete an item from Listview, and at a time Refresh Listview after deleting an item. How to possible?
I am using get all item using JSON Parsing from database and delete an selected an item on click of button. delete successfully from database but Listview not refresh at a time. how to do?
I am using Json Parsing. not local database.
In This case, How to refresh Listview when Deleting Item?
please Guide me.
Thanks in Advance.
My Code is,
Detail.java File
public class Detail extends Activity {
ListView lstDetail = null;
/** String */
String urlGetDetailData = null;
/** Declare another variable for Listview */
Adapter1 adapter1 = null;
ArrayList<Detail> myList = new ArrayList<Detail>();
/** Hashmap for ListView */
ArrayList<HashMap<String, String>> dataList = null;
/** JSON Node names */
public static final String TAG_MEMBER_ID = "mem_id";
public static final String TAG_ID = "id";
public static final String TAG_USER_ID = "userid";
public static final String TAG_STATUS = "Status";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
onCreateActivity(R.layout.detail);
initializeWidgets();
}
private void initializeWidgets() {
/** ListView */
lstDetail = (ListView) findViewById(R.id.lstDetail);
urlGetDetailData = "http://example.com/getdata.php?id="
+ strId;
new GetDetailData().execute();
myList.remove(position);
Adapter1.this.notifyDataSetChanged();
}
/**
* Async task class to get json by making HTTP call
* */
private class GetDetailData extends AsyncTask<Void, Void, Void> {
JSONObject jsonobject;
JSONArray jsonarray;
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0) {
dataList = new ArrayList<HashMap<String, String>>();
// Retrieve JSON Objects from the given URL address
jsonobject = JSONFunctions.getJSONfromURL(urlGetDetailData);
try {
// Locate the array name in JSON
jsonarray = jsonobject.getJSONArray("data");
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonarray.getJSONObject(i);
// Retrive JSON Objects
map.put("mem_id", String.valueOf(jsonobject
.getString(TAG_MEMBER_ID)));
map.put("id",
jsonobject.getString(TAG_ID));
map.put("userid", jsonobject.getString(TAG_USER_ID));
map.put("Status", jsonobject.getString(TAG_STATUS));
dataList.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (dataList.size() != 0) {
lstDetail.setVisibility(View.VISIBLE);
Adapter1 = new Adapter1(Detail.this,
dataList);
lstDetail.setAdapter(Adapter1);
} else {
lstDetail.setVisibility(View.GONE);
}
}
}
}
And Adapter Class is,
Adapter1.java File
public class Adapter1 extends BaseAdapter {
public ArrayList<HashMap<String, String>> arrData = null;
Context context = null;
LayoutInflater layoutInflater = null;
HashMap<String, String> getDetailData = new HashMap<String, String>();
/** String */
String strMemberId = null, urlDelete = null;
/** Constructor */
public Adapter1(Context context,
ArrayList<HashMap<String, String>> arrData) {
layoutInflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.context = context;
this.arrData = arrData;
}
#Override
public int getCount() {
return arrData.size();
}
#Override
public Object getItem(int position) {
return arrData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder = null;
if (convertView == null) {
convertView = layoutInflater.inflate(
R.layout.list_item, null);
viewHolder = new ViewHolder();
getData = arrData.get(position);
/** Initialize Widgets */
viewHolder.imgCancel = (ImageView) convertView
.findViewById(R.id.imgCancel);
viewHolder.imgCancel
.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
strMemberId = arrData.get(
position).get(
Detail.TAG_MEMBER_ID);
urlDelete = "http://example.com/delete.php?mem_id="
+ strMemberId;
new DeleteComments().execute();
}
});
/** TextView */
viewHolder.txtMemberId = (TextView) convertView
.findViewById(R.id.txtMemberId);
viewHolder.txtId = (TextView) convertView
.findViewById(R.id.txtId);
viewHolder.txtDesc = (TextView) convertView
.findViewById(R.id.txtDesc);
/** Set Value */
viewHolder.txtMemberId.setText(getDetailData
.get(Detail.TAG_MEMBER_ID));
viewHolder.txtId.setText(getDetailData
.get(Detail.TAG_ID));
viewHolder.txtDesc.setText(getDetailData
.get(Detail.TAG_STATUS));
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
return convertView;
}
/** ViewHolder Class */
#SuppressLint("NewApi")
public static class ViewHolder {
ImageView imgCancel = null;
TextView txtMemberId = null, txtId = null,txtDesc = null;
}
public class DeleteComments extends AsyncTask<Void, Void, Void> {
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0) {
ServiceHandler sh = new ServiceHandler();
String jsonStr = sh.makeServiceCall(urlDelete,
ServiceHandler.GET);
Log.d("Response : delete join comments", ">" + jsonStr);
return null;
}
protected void onPostExecute(Void result) {
super.onPostExecute(result);
};
}
}
detail.xml File is,
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/re/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<ListView
android:id="#+id/lstDetail"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
</ListView>
</RelativeLayout>
list_item.xml file is,
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/re/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<LinearLayout
android:id="#+id/contentLayout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:orientation="vertical" >
<TextView
android:id="#+id/txtId"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="111" />
<TextView
android:id="#+id/txtDesc"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</LinearLayout>
<ImageView
android:id="#+id/imgCancel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:src="#drawable/cancel" />
<TextView
android:id="#+id/txtMemberId"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/txtUserEventId"
android:layout_alignBottom="#+id/txtUserEventId"
android:layout_alignParentLeft="true"
android:text="222" />
</RelativeLayout>
in your custom adapter call this.notifyDataSetChanged(); where you are performing delete functionality and deleting that element from arrayList which is set to that adapter
You are writing delete action, in that function only call adapter.notifyDataSetChanged again.So it refr
on delete action fetch the data once again and then again call adapter.notifyDataSetChanged it will work
First of all Put you adapter code in Details.java class
then change this,
public class DeleteComments extends AsyncTask<Void, Void, Void> {
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0) {
ServiceHandler sh = new ServiceHandler();
String jsonStr = sh.makeServiceCall(urlDelete,
ServiceHandler.GET);
Log.d("Response : delete join comments", ">" + jsonStr);
return null;
}
protected void onPostExecute(Void result) {
super.onPostExecute(result);
Adapter1.remove(Adapter1.getItem(position));
};
}
hope it will help you
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder = null;
if (convertView == null) {
convertView = layoutInflater.inflate(
R.layout.list_item, null);
viewHolder = new ViewHolder();
getData = arrData.get(position);
/** Initialize Widgets */
viewHolder.imgCancel = (ImageView) convertView
.findViewById(R.id.imgCancel);
viewHolder.imgCancel
.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
strMemberId = arrData.get(
position).get(
Detail.TAG_MEMBER_ID);
urlDelete = "http://example.com/delete.php?mem_id="
+ strMemberId;
new DeleteComments().execute();
}
});
/** TextView */
viewHolder.txtMemberId = (TextView) convertView
.findViewById(R.id.txtMemberId);
viewHolder.txtId = (TextView) convertView
.findViewById(R.id.txtId);
viewHolder.txtDesc = (TextView) convertView
.findViewById(R.id.txtDesc);
/** Set Value */
viewHolder.txtMemberId.setText(getDetailData
.get(Detail.TAG_MEMBER_ID));
viewHolder.txtId.setText(getDetailData
.get(Detail.TAG_ID));
viewHolder.txtDesc.setText(getDetailData
.get(Detail.TAG_STATUS));
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
bDelete.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View view)
{
arrData.remove(position);
notifyDataSetChanged():
}
});
return convertView;
}
Why make it that complicated?
Just call remove(Obj); in OnClickListener of your customized adapter Adapter1's. And notifyDataSetChanged will be called in removed method too.