multiple alert dialog with list view - java

hi i am trying to add a list view to an alert dialog. on click of the ok button on my first alert dialog, the program directs to the response fragment which contains a second dialog box which needs to be populated with the list view. the problem i am having is that i am getting an empty alert box with the list view showing behind it on the fragment
public class ResponseFragment extends Fragment {
ListView list;
private String urlString;
ArrayList<HashMap<String, String>> oslist = new ArrayList<HashMap<String, String>>();
#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_response, container, false);
list=(ListView)v.findViewById(R.id.listviewResp);
urlString = "http://172.20.10.5:1012/easyQ.svc/rest/reasons";
new getReasons().execute(urlString);
return v;
}
private class getReasons extends AsyncTask<String, Void, String> {
protected String doInBackground(String... strings) {
String stream;
String urlString = strings[0];
HTTPDataHandler hh = new HTTPDataHandler();
stream = hh.GetHTTPData(urlString);
// Return the data from specified url
System.out.println(stream);
return stream;
}
protected void onPostExecute(String stream) {
if (stream != null)
{
try
{
JSONObject object = new JSONObject(stream);
JSONArray array = object.getJSONArray("reasonsResult");
for(int i = 0 ; i < array.length(); i++) {
JSONObject reasonObj = array.getJSONObject(i);
String ID = reasonObj.getString("reason_leaving_id");
String reason = reasonObj.getString("description");
HashMap<String, String> map = new HashMap<String, String>();
map.put("description", reason);
map.put("id", ID);
oslist.add(map);
}
for(int i = 0; i < oslist.size(); i++)
{
ListAdapter adapter = new SimpleAdapter(getActivity(), oslist,
R.layout.dialog_list,
new String[] { "description"}, new int[] {
R.id.txtResp});
// alertDialog.setView(inflater.inflate(R.layout.fragment_response,null));
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String branchId = oslist.get(+position).get("id");
final SessionV globalVariable = (SessionV) getActivity().getApplicationContext();
globalVariable.setBranchId(branchId);
Fragment fragment = null;
fragment = new HomeFragment();
getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.container_body, fragment).commit();
}
});
}
AlertDialog alertDialog = new AlertDialog.Builder(
getActivity()).create();
alertDialog.setTitle("easyQ");
alertDialog.setMessage("reason");
LayoutInflater inflater = (getActivity()).getLayoutInflater();
final View dialogView=inflater.inflate(R.layout.fragment_response,null);
alertDialog.setView(dialogView);
alertDialog.show();
alertDialog.show();
}
catch(JSONException e)
{
e.printStackTrace();
}
}
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/listviewResp"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingTop="15dp"
android:layout_centerVertical="true"
android:layout_alignParentStart="true" />
</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<TextView
android:id="#+id/txtResp"
android:layout_width="match_parent"
android:layout_height="?listPreferredItemHeightSmall"
android:checkMark="?android:attr/listChoiceIndicatorSingle"
android:gravity="center_vertical"
android:paddingLeft="?listPreferredItemPaddingLeft"
android:paddingRight="?listPreferredItemPaddingRight"
android:textAppearance="?textAppearanceListItemSmall" />
</LinearLayout>

I think you want to show a ListView inside the AlertDialog . So, You need to modify some of your code.
1st :
You inflate the listview from the fragment_response layout. Which is not necessary. In onCreateView() method just initialize a new object of ListView.
Replace :
list=(ListView)v.findViewById(R.id.listviewResp);
By
list = new ListView(getActivity());
2nd:
Change this Code :
AlertDialog alertDialog = new AlertDialog.Builder(
getActivity()).create();
alertDialog.setTitle("easyQ");
alertDialog.setMessage("reason");
LayoutInflater inflater = (getActivity()).getLayoutInflater();
final View dialogView=inflater.inflate(R.layout.fragment_response,null);
alertDialog.setView(dialogView);
alertDialog.show();
alertDialog.show();
By
AlertDialog alertDialog = new AlertDialog.Builder(getActivity()).create();
alertDialog.setTitle("easyQ");
alertDialog.setMessage("reason");
alertDialog.setView(listView);
alertDialog.show();
If other code is ok, then i hope it will work well.

Related

How to solve "java.lang.IllegalStateException: ArrayAdapter requires the resource ID to be a TextView" error?

The code is based by tinder tutorial:
public class arrayadapter extends ArrayAdapter<cards>
{
Context context;
public arrayadapter(Context context, int resource_id, List<cards> items)
{
super(context,resource_id,items);
}
public View getview(int position, View convertview, ViewGroup parent)
{
cards card_item = getItem(position);
if (convertview == null)
{
convertview = LayoutInflater.from(getContext()).inflate(R.layout.item,parent,false);
}
TextView user_name =(TextView) convertview.findViewById(R.id.user_name);
ImageView user_image =(ImageView) convertview.findViewById(R.id.image);
user_name.setText(card_item.getUser_name());
user_image.setImageResource(R.mipmap.ic_launcher); // change in the future with user pic
return convertview;
}
}
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="40sp"
android:paddingRight="40sp"
android:paddingTop="20sp"
android:paddingBottom="20sp"
android:outlineProvider="bounds"
android:clipToPadding="false"
>
<androidx.cardview.widget.CardView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
app:cardCornerRadius="6dp"
android:elevation="2dp"
android:id="#+id/card_view"
>
<FrameLayout
android:layout_gravity="center"
android:layout_width="250dp"
android:layout_height="170dp"
>
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/image">
</ImageView>
<TextView
android:id="#+id/user_name"
android:textSize="40sp"
android:textColor="#android:color/black"
android:gravity="center"
tools:text="hello"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</FrameLayout>
</androidx.cardview.widget.CardView>
</LinearLayout>
This are the swipe, arrayadapter classes and item xml. The data of the users are not important right now.
public class swipe_cards extends AppCompatActivity {
private cards cards_data[] ;
private arrayadapter arrayadapter;
private int i;
ListView listView;
List<cards>rowitems;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_swipe_cards);
Bundle extras = getIntent().getExtras();
rowitems = new ArrayList<cards>();
//arrayadapter = new arrayadapter (this,R.layout.item,rowitems);
//context,YourCustomLayoutID,TextViewIDinYourLayout,ListData
arrayadapter = new arrayadapter(this,R.layout.item,rowitems);
// ArrayAdapter arrayAdapter = new ArrayAdapter(MainActivity.this,
// R.layout.layout_item_autocomplete, R.id.tvCustom, getResources().getStringArray(R.array.sweets));
SwipeFlingAdapterView flingContainer =(SwipeFlingAdapterView)findViewById(R.id.frame);
flingContainer.setAdapter(arrayadapter);
flingContainer.setFlingListener(new SwipeFlingAdapterView.onFlingListener() {
#Override
public void removeFirstObjectInAdapter() {
// this is the simplest way to delete an object from the Adapter (/AdapterView)
Log.d("LIST", "removed object!");
rowitems.remove(0);
arrayadapter.notifyDataSetChanged();
}
#Override
public void onLeftCardExit(Object dataObject) {
//Do something on the left!
//You also have access to the original object.
//If you want to use it just cast it (String) dataObject
Toast.makeText(swipe_cards.this, "Left!",Toast.LENGTH_SHORT).show();
}
#Override
public void onRightCardExit(Object dataObject) {
Toast.makeText(swipe_cards.this, "Right!",Toast.LENGTH_SHORT).show();
}
#Override
public void onAdapterAboutToEmpty(int itemsInAdapter) {
// Ask for more data here
//rowitems.add("XML ".concat(String.valueOf(i)));
arrayadapter.notifyDataSetChanged();
Log.d("LIST", "notified");
i++;
}
#Override
public void onScroll(float scrollProgressPercent) {
}
});
// Optionally add an OnItemClickListener
flingContainer.setOnItemClickListener(new SwipeFlingAdapterView.OnItemClickListener() {
#Override
public void onItemClicked(int itemPosition, Object dataObject) {
Toast.makeText(swipe_cards.this, "Clicked!",Toast.LENGTH_SHORT).show();
}
});
if (extras != null)
{
ArrayList<String> users= extras.getStringArrayList("potential_users");
for (int counter = 0; counter < users.size(); counter++) {
String user = users.get(counter);
//String[] user_details= user.split(":");
String[] user_details = user.split(",");
String [] name_parmetrs= user_details[0].split(":");
String user_name= name_parmetrs[1];
cards card = new cards("222",user_name);
rowitems.add(card);
arrayadapter.notifyDataSetChanged();
}
}
}
You are creating an array adapter with the contructor where u are just giving 3 parameters- context, layout Id and the row-Items.
So for your constructor with only 3 parameters R.layout.item must be the id of a XML layout file containing only a TextView(the TextView can't be wrapped by another layout, like a LinearLayout, RelativeLayout etc!), something like this:
But in your case, you are using a complex layout So in that case you need to pass both layout id and Textview id in the constructor.
In case u need you don't have textViewId you can pass textViewId as 0.
like this
public arrayadapter(Context context, int resource_id, List<cards> items)
{
super(context,resource_id,0,items);
}
If u have a textview ResourceId you can pass the resourceid in place of 0
public arrayadapter(Context context, int resource_id,int textViewId, List<cards> items)
{
super(context,resource_id,textViewId,items);
}

setOnItemClickListener don't work on ListView in Fragment

When I click the listview in tab Fragment 1 it won't work jump into next activities. I already setOnItemClickListener in the class, but still won't work. Now my problem is when I click the listview it won't work.
public class TabFragment1_Staff extends Fragment {
ListView lsReport;
ArrayList<HashMap<String, String>> reportlist;
public View onCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
return inflater.inflate(R.layout.activity_tab_fragment1__staff, container, false);
}
#Override
public void onActivityCreated(Bundle savedInstanceState){
super.onActivityCreated(savedInstanceState);
reportlist = new ArrayList<>();
lsReport = getActivity().findViewById(R.id.listReport);
loadReport();
lsReport.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(getActivity(),AddStatusDialogWindow.class);
Bundle bundle = new Bundle();
Log.e("HANIS",reportlist.get(position).get("reportID"));
bundle.putString("reportID",reportlist.get(position).get("reportID"));
bundle.putString("fullName",reportlist.get(position).get("fullName"));
bundle.putString("icNum",reportlist.get(position).get("icNum"));
bundle.putString("phoneNum",reportlist.get(position).get("phoneNum"));
bundle.putString("Rdate",reportlist.get(position).get("Rdate"));
bundle.putString("Rtime",reportlist.get(position).get("Rtime"));
bundle.putString("timeName",reportlist.get(position).get("timeName"));
bundle.putString("typeVehicle",reportlist.get(position).get("typeVehicle"));
bundle.putString("registrationnum",reportlist.get(position).get("registrationnum"));
bundle.putString("location",reportlist.get(position).get("location"));
bundle.putString("brief",reportlist.get(position).get("brief"));
intent.putExtras(bundle);
startActivity(intent);
}
});
}
}
tabFragment1.xml
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<ListView
android:id="#+id/listReport"
android:layout_width="match_parent"
android:layout_height="300dp"
android:clickable="false"
android:focusable="false"
android:focusableInTouchMode="false"/>
</LinearLayout>
</ScrollView>
LoadReport class
class LoadReport extends AsyncTask<Void, Void, String> {
#Override
protected String doInBackground(Void... params) {
// Perform api call
}
#Override
protected void onPostExecute(String s) {
reportlist.clear();
// Parse api response and fill in reportlist var
ListAdapter adapter = new CustomList_StatusReport(
getActivity(), reportlist,
R.layout.activity_custom_list__status_report, new String[]
{"reportID","fullName","icNum","phoneNum"}, new int[]
{R.id.tvReport_ID,R.id.tvCompliantName,R.id.tvCompliantIC,R.id.tvCompliantPhone});
lsReport.setAdapter(adapter);
Toast.LENGTH_SHORT).show();
}
}
LoadReport loadReport = new LoadReport();
loadReport.execute();
}
public class CustomList_StatusReport extends SimpleAdapter {
private Context mContext;
public LayoutInflater inflater = null;
public CustomList_StatusReport(Context context, List<? extends Map<String, ?>> data, int resource, String[] from, int[] to) {
super(context, data, resource, from, to);
mContext = context;
inflater = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View vi=convertView;
try {
if (convertView == null)
vi = inflater.inflate(R.layout.activity_custom_list__status_report, null);
HashMap<String, Object> data = (HashMap<String, Object>) getItem(position);
TextView reportID = vi.findViewById(R.id.tvReport_ID);
TextView cName = vi.findViewById(R.id.tvCompliantName);
TextView cIC = vi.findViewById(R.id.tvCompliantIC);
TextView cPhone = vi.findViewById(R.id.tvCompliantPhone);
String id = (String) data.get("reportID");
String name = (String)data.get("fullName");
String ic = (String)data.get("icNum");
String phone = (String)data.get("phoneNum");
reportID.setText(id);
cName.setText(name);
cIC.setText(ic);
cPhone.setText(phone);
}catch (IndexOutOfBoundsException e){}
return vi;
}
In tabFragment1.xml, why you are using the below lines code?
android:clickable="false"
android:focusable="false"
android:focusableInTouchMode="false"
Please remove these if not needed and let us know whether this issue exists?

No virtual method getLayoutInflater [duplicate]

This question already has answers here:
getLayoutInflater() in fragment
(5 answers)
Closed 4 years ago.
I'm trying to code an app that downloads data of some events from an online MySQL database and writes it into my android app. Right now, what i'm trying to do is just testing if downloading the name of the event works, but i keep getting this error:
java.lang.NoSuchMethodError: No virtual method getLayoutInflater()Landroid/view/LayoutInflater; in class Lcom/suspicio/appfisio_business/FrammentoCorsi; or its super classes (declaration of 'com.suspicio.appfisio_business.FrammentoCorsi' appears in /data/app/com.suspicio.appfisio_business-1/split_lib_slice_8_apk.apk)
at com.suspicio.appfisio_business.FrammentoCorsi$EventoAdapter.getView(FrammentoCorsi.java:204)
which points to the line:
listViewItem = getLayoutInflater().inflate(R.layout.frammento_corsi, null, true);
Here's my code (it's a fragment):
FrammentoCorsi.java:
public class FrammentoCorsi extends Fragment {
public static final int CODE_GET_REQUEST = 1024;
public static final int CODE_POST_REQUEST = 1025;
public FrammentoCorsi() { //Vuoto
}
boolean isUpdating = false;
View rootView;
List<Evento> eventoList;
ListView listView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.frammento_corsi, container, false);
listView = (ListView) rootView.findViewById(R.id.listViewEventi);
return rootView;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
eventoList = new ArrayList<>();
readEventi();
}
private void readEventi() {
PerformNetworkRequest request = new PerformNetworkRequest(Api.URL_READ_EVENTI, null, CODE_GET_REQUEST);
request.execute();
}
private void refreshEventoList(JSONArray eventi) throws JSONException {
//clearing previous heroes
eventoList.clear();
//traversing through all the items in the json array
//the json we got from the response
for (int i = 0; i < eventi.length(); i++) {
//getting each hero object
JSONObject obj = eventi.getJSONObject(i);
//adding the hero to the list
eventoList.add(new Evento(
obj.getInt("id"),
obj.getString("titolo"),
obj.getString("inizio"),
obj.getString("fine"),
obj.getInt("categoria"),
obj.getString("link"),
obj.getString("luogo")
));
}
//creating the adapter and setting it to the listview
EventoAdapter adapter = new EventoAdapter(eventoList);
listView.setAdapter(adapter);
}
//inner class to perform network request extending an AsyncTask
public class PerformNetworkRequest extends AsyncTask<Void, Void, String> {
//the url where we need to send the request
String url;
//the parameters
HashMap<String, String> params;
//the request code to define whether it is a GET or POST
int requestCode;
ProgressBar barra = (ProgressBar) getView().findViewById(R.id.progressBar);
//constructor to initialize values
PerformNetworkRequest(String url, HashMap<String, String> params, int requestCode) {
this.url = url;
this.params = params;
this.requestCode = requestCode;
}
//when the task started displaying a progressbar
#Override
protected void onPreExecute() {
super.onPreExecute();
barra.setVisibility(View.VISIBLE);
}
//this method will give the response from the request
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
barra.setVisibility(View.INVISIBLE);
try {
JSONObject object = new JSONObject(s);
if (!object.getBoolean("error")) {
Toast.makeText(getActivity().getApplicationContext(), object.getString("message"), Toast.LENGTH_SHORT).show();
refreshEventoList(object.getJSONArray("eventi"));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
//the network operation will be performed in background
#Override
protected String doInBackground(Void... voids) {
RequestHandler requestHandler = new RequestHandler();
if (requestCode == CODE_POST_REQUEST)
return requestHandler.sendPostRequest(url, params);
if (requestCode == CODE_GET_REQUEST)
return requestHandler.sendGetRequest(url);
return null;
}
}
class EventoAdapter extends ArrayAdapter<Evento> {
List<Evento> eventoList;
//constructor to get the list
public EventoAdapter(List<Evento> eventoList) {
super(getActivity(), R.layout.frammento_corsi, eventoList);
this.eventoList = eventoList;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View listViewItem = convertView;
if (listViewItem == null) {
listViewItem = getLayoutInflater().inflate(R.layout.frammento_corsi, null, true);
}
//getting the textview for displaying name
TextView textViewName = listViewItem.findViewById(R.id.nomeeventocalendario);
//the update and delete textview
//ImageView textViewUpdate = listViewItem.findViewById(R.id.notifica);
//ImageView textViewDelete = listViewItem.findViewById(R.id.link);
final Evento evento = eventoList.get(position);
textViewName.setText(evento.getTitolo());
return listViewItem;
}
}
}
And its resource file frammento_corsi.xml:
<?xml version="1.0" encoding="utf-8"?>
<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"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context="com.suspicio.appfisio_business.FrammentoCorsi">
<ListView
android:id="#+id/listViewEventi"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:id="#+id/nomeeventocalendario"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<ProgressBar
android:id="#+id/progressBar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:visibility="gone"/>
</FrameLayout>
Can you help me out?
Thanks in advance!
Use this
LayoutInflater layoutInflater = LayoutInflater.from(getContext());
listViewItem = layoutInflater.inflate(R.layout.frammento_corsi, null ,true);
Instead of this
listViewItem = getLayoutInflater().inflate(R.layout.frammento_corsi, null, true);

ListView OnItemClickListener Crash when selecting json object

The application crashes when I tried to retrieve the JSON object to be used from searchActivity.java to searchDetail.java. It seems that the function getInfo() causes this problem. Initially, the list_data in getInfo() has size of 10, however after calling it from the searchActivity.java, the size becomes 0. Thus, may I know what can I do to solve this problem?
DataParser.java
public class DataParser extends AsyncTask<Void,Void,Integer> {
Context c;
ArrayList<Herb> herb=new ArrayList<>();
ArrayList<HashMap<String, String>> list_data = new ArrayList<HashMap<String, String>>();
HashMap<String,String> data = new HashMap<>();
public DataParser(ListView lv){
this.lv = lv;
}
public DataParser(Context c, String jsonData, ListView lv) {
this.c = c;
this.jsonData = jsonData;
this.lv = lv;
}
#Override
protected Integer doInBackground(Void... params) {
return this.parseData();
}
#Override
protected void onPostExecute(Integer result) {
super.onPostExecute(result);
pd.dismiss();
if(result==0)
{
Toast.makeText(c,"Unable To Parse",Toast.LENGTH_SHORT).show();
}else {
//BIND DATA TO LISTVIEW
CustomAdapter adapter=new CustomAdapter(c,herb);
lv.setAdapter(adapter);
}
}
private int parseData()
{
try
{
JSONArray ja=new JSONArray(jsonData);
JSONObject jo=null;
herb.clear();
Herb Herb;
for(int i=0;i<ja.length();i++)
{
jo=ja.getJSONObject(i);
String id=jo.getString("h_id");
String name=jo.getString("h_name");
String imageUrl=jo.getString("h_image");
Herb=new Herb();
Herb.setId(id);
Herb.setName(name);
Herb.setImageUrl(imageUrl);
herb.add(Herb);
data.put("id",id);
data.put("name",name);
data.put("imageUrl",imageUrl);
list_data.add(data);
}
DataStorage.map = getInfo();
return 1;
} catch (JSONException e) {
e.printStackTrace();
}
return 0;
}
public ArrayList<HashMap<String, String>> getInfo(){
return this.list_data = list_data;
}
}
searchActivity.java
public class searchActivity extends AppCompatActivity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
ListView lv= (ListView) findViewById(R.id.HerbListView);
Downloader dl = new Downloader(searchActivity.this,urlAddress,lv);
dl.execute();
final DataParser dp = new DataParser(lv);
lv.setOnItemClickListener (new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
try{
ArrayList<HashMap<String, String>> list_data = DataStorage.map;
String hid = list_data.get(position).get("id");
String name = list_data.get(position).get("name");
String imageUrl = list_data.get(position).get("imageUrl");
Intent intent = new Intent(searchActivity.this, searchDetail.class);
intent.putExtra("id", hid);
intent.putExtra("name", name);
intent.putExtra("imageUrl", imageUrl);
startActivity(intent);
}
catch (NullPointerException e){
e.printStackTrace();
}
}
});
}
}
searchDetail.java
public class searchDetail extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search_detail);
String name = getIntent().getStringExtra("name");
String imageUrl = getIntent().getStringExtra("imageUrl");
TextView txt1= (TextView) findViewById(R.id.txtHName);
ImageView img= (ImageView) findViewById(R.id.imageHerb);
txt1.setText(name);
Picasso.with(this).load(imageUrl).fit().into(img);
}
}
DataStorage.java
public class DataStorage {
public static ArrayList<HashMap<String,String>> map = new ArrayList<>();
}
activity_search_detail.xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<ImageView
android:id="#+id/imageHerb"
android:layout_width="200dp"
android:layout_height="200dp"
android:layout_centerHorizontal="true"
android:scaleType="fitXY" />
<TextView
android:id="#+id/lblHName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/imageHerb"
android:paddingTop="10dp"
android:text="Herb Name: " />
<TextView
android:id="#+id/txtHName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/imageHerb"
android:layout_toEndOf="#id/lblHName"
android:paddingTop="10dp"
android:text="TextView" />
</RelativeLayout>
current logcat generated
java.lang.IllegalStateException: Circular dependencies cannot exist in RelativeLayout
P/S: I cant find any circular dependencies in the activity_search_detail.xml
First execute the DataParser class ..new DataParser( lv).execute() or in ur case dp.execute() u are missing this statement.. If you are not executing the AsyncTask class it wont do any task in doInBackground(). Hopefully it will solve your problem.. dp.getinfo() will always return a blank list... make another class called class holdHashmapList {
public static ArrayList<Hashmap<String,String>> map= new ArrayList<>();} and in dataParser class holdHashmapList.map =getInfo();} and in onItemClick listener...Arralist<map<>> = holdHashmapList.map; Your hashmap that u are building will always contain the last last object... in parseData function... so before of data.put("id"); just add data=new HashMap<>();
you have to execute DataParser(dp) in order to populate your list_data in SearchActivity. only initializing DataParser won't populate the list_data.
public class searchActivity extends AppCompatActivity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
ListView lv= (ListView) findViewById(R.id.HerbListView);
Downloader dl = new Downloader(searchActivity.this,urlAddress,lv);
dl.execute();
final DataParser dp = new DataParser(lv);
dp.execute(); // update
lv.setOnItemClickListener (new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long
id) {
try{
ArrayList<HashMap<String, String>> list_data = dp.getInfo();
String hid = list_data.get(position).get("id");
String name = list_data.get(position).get("name");
String imageUrl = list_data.get(position).get("imageUrl");
Intent intent = new Intent(searchActivity.this, searchDetail.class);
intent.putExtra("id", hid);
intent.putExtra("name", name);
intent.putExtra("imageUrl", imageUrl);
startActivity(intent);
}
catch (NullPointerException e){
e.printStackTrace();
}
}
});
}

Android: calling getview() for ListView's Adapter from Fragment in viewPager

I have ViewPager that containing 3 different Fragment. each Fragment containing A Different View and also ListView, I got a problem when I was trying to show the ListView in one of Fragment from ViewPager, it doesn't show anything. I've tried to debug my adapter and it seems my getView() method is not called. I try to call my Fragment not from ViewPager, the result is getView() is called from adapter and ListView is showing. Is there any problem to show ListView from ViewPager? I have tried this solution by calling my adapter from onViewCreated() but there's nothing change. so is there any wrong with my method? this is my code :
My Fragment Class for Managing ViewPager
public class Frag_Provider extends Fragment {
private String[] tabsTitles = {"TERDEKAT", "SEMUA", "PROVIDERKU"};
String url = "";
List<ModelProvider> list_provider;
DB_Esehat db_esehat = null;
SQLiteDatabase db = null;
ContentLoadingProgressBar progressbar;
TabLayout tabLayout;
ViewPager pager;
public Frag_Provider (){
}
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
((MainActivity) getActivity()).custom_toolbar("Provider", R.color.toolbar_provider, R.color.toolbar_provider_dark);
View result=inflater.inflate(R.layout.fragment_provider, container, false);
list_provider = new ArrayList<ModelProvider>();
progressbar = (ContentLoadingProgressBar)result.findViewById(R.id.progressbar);
db_esehat = new DB_Esehat(getActivity());
db = db_esehat.getWritableDatabase();
db.delete("LST_PROVIDER", null, null);
pager=(ViewPager)result.findViewById(R.id.pager);
tabLayout = (TabLayout)result.findViewById(R.id.sliding_tabs);
url = getResources().getString(R.string.url_host)+getResources().getString(R.string.url_provider);
new ProviderTask(url).execute();
pager.setAdapter(buildAdapter(tabsTitles));
tabLayout.post(new Runnable() {
#Override
public void run() {
tabLayout.setupWithViewPager(pager);
}
});
return(result);
}
public class ProviderTask extends AsyncTask<String, Void, String> {
String url = "";
public ProviderTask(String url) {
this.url = url;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
progressbar.setVisibility(View.VISIBLE);
}
#Override
protected String doInBackground(String... params) {
String result = "";
try {
result = Connection.get(url);
} catch (Exception e) {
result = "";
}
return result;
}
#Override
protected void onPostExecute(String result) {
progressbar.setVisibility(View.GONE);
pager.setVisibility(View.VISIBLE);
tabLayout.setVisibility(View.VISIBLE);
super.onPostExecute(result);
if (result.equals("") || result.equals(null)) {
MethodSupport.AlertDialog(getActivity());
} else {
try {
JSONArray Data = new JSONArray(result);
for (int i = 0; i < Data.length(); i++) {
String LSKA_NOTE = "";
String RSALAMAT = "";
String RSTELEPON = "";
String RSNAMA = "";
String MAPPOS = "";
int RSTYPE = 0;
int RSID = 0;
int RS_NTT = 0;
JSONObject json = Data.getJSONObject(i);
if (json.has("LSKA_NOTE")) {
LSKA_NOTE = json.getString("LSKA_NOTE");
}
if (json.has("RSALAMAT")) {
RSALAMAT = json.getString("RSALAMAT");
}
if (json.has("RSTELEPON")) {
RSTELEPON = json.getString("RSTELEPON");
}
if (json.has("RSNAMA")) {
RSNAMA = json.getString("RSNAMA");
}
if (json.has("MAPPOS")) {
MAPPOS = json.getString("MAPPOS");
}
if (json.has("RSTYPE")) {
RSTYPE = json.getInt("RSTYPE");
}
if (json.has("RSID")) {
RSID = json.getInt("RSID");
}
if (json.has("RS_NTT")) {
RS_NTT = json.getInt("RS_NTT");
}
db_esehat.InsertRS(LSKA_NOTE, RSALAMAT, RSTELEPON, RSNAMA, MAPPOS, RSTYPE, RSID, RS_NTT);
}
} catch (Exception e) {
Log.d("TES", e.getMessage());
}
}
}
}
private PagerAdapter buildAdapter(String[] tabsTitles) {
return(new FragmentStatePagerAdapter(getActivity(), getChildFragmentManager(),tabsTitles));
}
}
This is FragmentStatePagerAdapter.java
public class FragmentStatePagerAdapter extends FragmentPagerAdapter {
Context ctxt=null;
private String[] tabsTitles;
public FragmentStatePagerAdapter(Context ctxt, FragmentManager mgr, String[] tabsTitles) {
super(mgr);
this.ctxt=ctxt;
this.tabsTitles = tabsTitles;
}
#Override
public int getCount() {
return tabsTitles.length;
}
#Override
public Fragment getItem(int position) {
switch(position) {
case 0:
return Frag_Provider_Terdekat.newInstance(position);
case 1:
return Frag_Provider_Semua.newInstance(position);
case 2:
return Frag_Provider_Ku.newInstance(position);
}
return null;
}
// #Override public float getPageWidth(int position) { return(0.7f); }
#Override
public String getPageTitle(int position) {
return tabsTitles[position];
}
}
this is my Fragment_Provider.xml, Layout for managing my ViewPager
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v4.widget.ContentLoadingProgressBar
android:id="#+id/progressbar"
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:visibility="gone"
android:indeterminate="false" />
<android.support.design.widget.TabLayout
android:id="#+id/sliding_tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabMaxWidth="0dp"
app:tabGravity="fill"
style="#style/MyCustomTabLayout"
app:tabMode="fixed"
android:fillViewport="true"
android:visibility="gone" />
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="fill_parent"
android:layout_height="0px"
android:layout_weight="1"
android:background="#android:color/white"
android:layout_below="#id/sliding_tabs"
android:visibility="gone"/>
</RelativeLayout>
This is of my Fragment in ViewPagerthat containing ListView :
public class Frag_Provider_Terdekat extends Fragment {
private static final String KEY_POSITION="position";
private ListView list_provider;
List<ModelProviderTerdekat> list_ekamedicare;
DB_Esehat db_esehat;
SQLiteDatabase db;
ProviderTerdekatAdapter adapter;
static Frag_Provider_Terdekat newInstance(int position) {
Frag_Provider_Terdekat frag=new Frag_Provider_Terdekat();
Bundle args=new Bundle();
args.putInt(KEY_POSITION, position);
frag.setArguments(args);
return(frag);
}
static String getTitle(Context ctxt, int position) {
return("PROVIDER KU");
}
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
View result=inflater.inflate(R.layout.fragment_child_providerterdekat, container, false);
list_provider = (ListView)result.findViewById(R.id.list_provider);
list_ekamedicare = new ArrayList<ModelProviderTerdekat>();
db_esehat = new DB_Esehat(getActivity());
list_ekamedicare = db_esehat.getProvider();
adapter = new ProviderTerdekatAdapter(getActivity().getApplicationContext(), R.layout.adapter_provider, list_ekamedicare);
list_provider.setAdapter(adapter);
return result;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
#Override
public void onDetach() {
super.onDetach();
}
}
and this is Adapter for my ListView
public class ProviderTerdekatAdapter extends ArrayAdapter<ModelProviderTerdekat> {
List<ModelProviderTerdekat> data = Collections.emptyList();
private LayoutInflater inflater;
private Context context;
static class ViewHolder {
ImageView imvprov_map;
ImageView imvprov_fav;
TextView textprov_nama_rs;
TextView textprov_alamat_rs;
TextView textprov_km_rs;
}
public ProviderTerdekatAdapter (Context context, int viewResourceId, List<ModelProviderTerdekat> data) {
super(context, R.layout.adapter_provider, data);
this.context = context;
inflater = LayoutInflater.from(context);
this.data = data;
}
#Override
public int getCount() {
return data.size();
}
#Override
public long getItemId(int arg0) {
return 0;
}
#Override
public View getView(int position, View view, ViewGroup parent) {
if (view == null) {
view = inflater.inflate(R.layout.adapter_provider, parent, false);
ViewHolder viewHolder = new ViewHolder();
viewHolder.imvprov_map = (ImageView) view.findViewById(R.id.imvprov_map);
viewHolder.imvprov_fav = (ImageView) view.findViewById(R.id.imvprov_fav);
viewHolder.textprov_nama_rs = (TextView) view.findViewById(R.id.textprov_nama_rs);
viewHolder.textprov_alamat_rs = (TextView) view.findViewById(R.id.textprov_alamat_rs);
viewHolder.textprov_km_rs = (TextView) view.findViewById(R.id.textprov_km_rs);
view.setTag(viewHolder);
}
ViewHolder viewHolder = (ViewHolder) view.getTag();
viewHolder.textprov_nama_rs.setText(data.get(position).getRSNAMA());
viewHolder.textprov_alamat_rs.setText(data.get(position).getRSALAMAT());
return view;
}
}
I have no Idea why my GetView() not called in my Adapter, is it because I put in ViewPager? well I hope someone understand about it and help me to solver my problem. thank you very much.
Finally.. I found a solution for my problem, it's because I put ViewPager in RelativeLayout after I change into LinearLayout all view displayed as I wanted
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v4.widget.ContentLoadingProgressBar
android:id="#+id/progressbar"
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:visibility="gone"
android:indeterminate="false" />
<android.support.design.widget.TabLayout
android:id="#+id/sliding_tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabMaxWidth="0dp"
app:tabGravity="fill"
style="#style/MyCustomTabLayout"
app:tabMode="fixed"
android:fillViewport="true"
android:visibility="gone" />
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="fill_parent"
android:layout_height="0px"
android:layout_weight="1"
android:background="#android:color/white"
android:layout_below="#id/sliding_tabs"
android:visibility="gone"/>
</LinearLayout>

Categories

Resources