Main class
Using volley library to fetch JSON data from URL.
public class MyActivity extends Activity {
ListView listView;
List<Details> rowItems;
RequestQueue requestQueue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.details2);
url = getIntent().getStringExtra("key");
if(savedInstanceState!=null){
Log.d("STATE",savedInstanceState.toString());
}
requestQueue = Volley.newRequestQueue(this);
JsonObjectRequest jor = new JsonObjectRequest(url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray ja = response.getJSONArray("results");
ArrayList<Details> myModelList = new ArrayList<Details>();
Details mymodel = null;
for (int i = 0; i < ja.length(); i++) {
JSONObject jsonObject = ja.getJSONObject(i);
mymodel = new Details();
mymodel.id = Integer.parseInt(jsonObject.optString("id").toString());
mymodel.url = jsonObject.getString("resLink");
mymodel.resType = jsonObject.getString("resType");
mymodel.name = jsonObject.getString("resName");
myModelList.add(mymodel);
setData();
}
}catch(JSONException e){e.printStackTrace();}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Volley","Error");
}
}
);
requestQueue.add(jor);
}
private void setData() {
listView = (ListView) findViewById(R.id.list);
CustomListViewAdapter adapter = new CustomListViewAdapter(this,
R.layout.list_item, rowItems);
listView.setAdapter(adapter);
//listView.setOnItemClickListener(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
My CustomListViewAdapter claas is below
public class CustomListViewAdapter extends ArrayAdapter<Details> {
Context context;
public CustomListViewAdapter(Context context, int resourceId,
List<Details> items) {
super(context, resourceId, items);
this.context = context;
}
/*private view holder class*/
private class ViewHolder {
TextView txtTitle;
TextView txtDesc;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
Details rowItem = getItem(position);
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.list_item, null);
holder = new ViewHolder();
holder.txtDesc = (TextView) convertView.findViewById(R.id.desc);
holder.txtTitle = (TextView) convertView.findViewById(R.id.title);
convertView.setTag(holder);
} else
holder = (ViewHolder) convertView.getTag();
holder.txtDesc.setText(rowItem.getResType());
holder.txtTitle.setText(rowItem.getName());
return convertView;
}
My Details class
public class Details extends Results {
String name;
String resType;
String url;
int id;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getResType() {
return resType;
}
public void setResType(String resType) {
this.resType = resType;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
* want to showthe data I received in list view*
my XML
<ListView
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
list_item.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/icon"
android:paddingBottom="10dp"
android:textColor="#CC0033"
android:textSize="16dp" />
<TextView
android:id="#+id/desc"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/title"
android:layout_toRightOf="#+id/icon"
android:paddingLeft="10dp"
android:textColor="#3399FF"
android:textSize="14dp" />
You are doing everything right but not passing your myModelList which contains the data and are passing the empty rowItems list. Once you fetch all data and create your myModelList, call
setData(myModelList);
And change your setData method as follows
private void setData(List<Details> mList) {
listView = (ListView) findViewById(R.id.list);
CustomListViewAdapter adapter = new CustomListViewAdapter(this,
R.layout.list_item, mList);
listView.setAdapter(adapter);
}
use following line in your adapter class getView()
Details rowItem = (Details) getItem(position);
instead of
Details rowItem = getItem(position);
Update your setData methode as you are not getting list to set data.
private void setData(List<Details> list) {
listView = (ListView) findViewById(R.id.list);
CustomListViewAdapter adapter = new CustomListViewAdapter(this,
R.layout.list_item, list);
listView.setAdapter(adapter);
}
Also change setData(); to setData(myModelList);
In adapter you are using List rowItems;
so code of onResponse method should be like as follows
JSONArray ja = response.getJSONArray("results");
rowItems = new ArrayList<Details>();
Details mymodel = null;
for (int i = 0; i < ja.length(); i++) {
JSONObject jsonObject = ja.getJSONObject(i);
mymodel = new Details();
mymodel.id = Integer.parseInt(jsonObject.optString("id").toString());
mymodel.url = jsonObject.getString("resLink");
mymodel.resType = jsonObject.getString("resType");
mymodel.name = jsonObject.getString("resName");
rowItems.add(mymodel);
}
setData();
To make the json parsing easy you can use Gson library as explained here
http://www.mysamplecode.com/2013/07/android-json-stream-data-parsing.html
Related
I have created an android application. in that application when I click on add, item added to the array list and this array list I want to show in Cart Activity. how to do that.
here is my activity1
public void addShirt(View view) {
MainActivity.cartItems.add(getString(R.string.shirt));
}
public void addPant(View view) {
MainActivity.cartItems.add(getString(R.string.pant));
}
public void view(View view) {
Intent i =new Intent(OnlyIron.this,CartActivity.class);
startActivity(i);
}
and cart activity is
for(int i=0; i<MainActivity.cartItems.size();i++) {
Toast.makeText(this, "item : " + MainActivity.cartItems.get(i), Toast.LENGTH_SHORT).show();
}
it showing toast but I enter code here want this show in listview
First lets Create model class and store data in it.
public class Cart {
private String id;
private String name;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Now to add items in that list i would call it this way :
private ArrayList<Cart > cart_array;
cart_array= new ArrayList<>();
Cart cart1 = new Cart ();
cart.setId("1");
cart.setName("first product");
Cart cart2 = new Cart ();
cart.setId("2");
cart.setName("first product");
Cart cart3 = new Cart ();
cart.setId("3");
cart.setName("first product");
//and than add your model into array
cart_array.add(cart1);
cart_array.add(cart2);
cart_array.add(cart3);
//and finaly set your adapter
Cart_Adapter adapter = new Cart_Adapter(cart_array, getActivity());
Recycler.setAdapter(adapter );
Please take a list view in CartActivity & create an Custom Adapter as according to your need(UI). Pass the MainActivity.cartItems this list to Adapter. It will start to show in your CartActivity.
You can see below example:
public class CustomAdapter extends BaseAdapter{
Activity mContext;
public ArrayList<String> mCartList = new ArrayList<String>();
private LayoutInflater mInflater=null;
public CustomAdapter(Activity activty, ArrayList<String> list)
{
this.mContext = activty;
mInflater = activty.getLayoutInflater();
this.mCartList=list;
}
#Override
public int getCount() {
if (mCartList != null){
return mCartList.size();
} else{
return 0;
}
}
#Override
public String getItem(int arg0) {
return mCartList.get(arg0);
}
#Override
public long getItemId(int index) {
return index;
}
#Override
public View getView(final int position, View convertView, ViewGroup arg2) {
final ViewHolder holder;
if (convertView == null ) {
holder = new ViewHolder();
convertView = mInflater.inflate(R.layout.item_layout, null);
holder.mItemNameTV= (TextView) convertView.findViewById(R.id.itemtv);
convertView.setTag(holder);
}
else {
holder = (ViewHolder) convertView.getTag();
}
holder.mNameTV.setText(mCartList.get(position));
return convertView;
}
private static class ViewHolder {
TextView mNameTV;
}
}
// Item Layout
<LinearLayout
android:layout_width="match_parent"
android:layout_height="#dimen/forty_dp"
android:gravity="center_horizontal"
android:orientation="vertical">
<TextView
android:id="#+id/fieldTV"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="#dimen/five_dp"
android:layout_weight="0.4"
android:padding="#dimen/ten_dp"
android:text="Custom Field"
android:textColor="#color/dark_gray_color"
android:textSize="#dimen/normal_font_size"
android:visibility="visible" />
</LinearLayout>
// Let Suppose your CartActivity is following:
ListView mListView = (ListView)findViewById(R.id.listview);
CustomAdapter adapter = new CustomAdapter(this, MainActivity.cartItems);
mListView.setAdapter(adapter);
Is there a way to choose a specific row of my RecyclerView (maybe by getting the index of the row) and then use it to create an intent.
I tried some things by getting the specific row information but that was not even close. My recycler is populated with data from a database.
To choose a specific row of my recycler, you can add setOnItemClickListener code like this one to your onCreate function:
listView_search.setOnItemClickListener(
new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id){
//Here I'm getting store_id and store_name
TextView store_search_id =(TextView) v.findViewById(R.id.store_search_id);
TextView store_search_name =(TextView) v.findViewById(R.id.store_search_name);
String store_name = store_search_name.getText().toString();
String store_id = store_search_id.getText().toString();
//Then I'm sending theses variables to a shared Intent
Intent myIntent = new Intent(getApplicationContext(), StoresShowActivity.class);
myIntent.putExtra("STORE_ID", store_id);
myIntent.putExtra("STORE_NAME", store_name);
startActivity(myIntent);
}
}
);
You may also want to follow these steps:
A. Add a layout for the Recycle view:
<?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:id="#+id/activity_stores_search"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="ksa.ikp.activities.StoresSearchActivity">
<SearchView
android:id="#+id/SearchView_store"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:iconifiedByDefault="false">
<requestFocus />
</SearchView>
<ListView
android:id="#+id/listView_search"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_below="#+id/SearchView_store" />
</RelativeLayout >
B. Add a layout for the recycleview item
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal"
android:padding="10dp">
<TextView
android:id="#+id/store_search_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="invisible" />
<TextView
android:id="#+id/store_search_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/store_search_category"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
C. Use adapter like this one and you can modify it based on your need
public class StoresSearchAdapter extends BaseAdapter {
// Declare Variables
Context mContext;
LayoutInflater inflater;
private List<Store> myList = null;
private ArrayList<Store> myArrayList;
public StoresSearchAdapter(Context context, List<Store> myList) {
mContext = context;
this.myList = myList;
inflater = LayoutInflater.from(mContext);
this.myArrayList = new ArrayList<Store>();
this.myArrayList.addAll(myList);
}
public class ViewHolder {
TextView store_search_id;
TextView store_search_name;
TextView store_search_category;
}
#Override
public int getCount() {
return myList.size();
}
#Override
public Store getItem(int position) {
return myList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(final int position, View view, ViewGroup parent) {
final ViewHolder holder;
if (view == null) {
holder = new ViewHolder();
view = inflater.inflate(R.layout.activity_stores_search_item, null);
// Locate the TextViews in activity_stores_search_item.xml
holder.store_search_id = (TextView) view.findViewById(R.id.store_search_id);
holder.store_search_name = (TextView) view.findViewById(R.id.store_search_name);
holder.store_search_category = (TextView) view.findViewById(R.id.store_search_category);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
// Set the results into TextViews
holder.store_search_id.setText(myList.get(position).getStr_id()+"");
holder.store_search_name.setText(myList.get(position).getStr_name());
String s = SplashActivity.db.getNameById(myList.get(position).getStr_cat_id()+"",SplashActivity.db.TABLE_CATEGORY,SplashActivity.db.COLUMN_CAT_NAME,SplashActivity.db.COLUMN_CAT_ID);
s = " in ("+ s + ")";
holder.store_search_category.setText(s);
return view;
}
// Filter Class
public void filter(String s) {
s = s.toLowerCase(Locale.getDefault());
myList.clear();
if (s.length() == 0) {
myList.addAll(myArrayList);
} else {
myList.addAll(SplashActivity.db.getAllStoresFiltered(s));
}
notifyDataSetChanged();
}
}
Finally your final output will be something like this one:
screenshot
This is my recyclerbackgroundtask
public class RecycleBackgroundTask extends AsyncTask{
Context ctx;
Activity activity;
RecyclerView recyclerView;
RecyclerView.Adapter adapter;
RecyclerView.LayoutManager layoutManager;
ArrayList<Post> arrayList = new ArrayList<>();
public RecycleBackgroundTask(Context ctx){
this.ctx = ctx;
activity = (Activity)ctx;
}
String json_string = "http://192.168.2.110/app/post.php";
#Override
public void onPreExecute() {
recyclerView = (RecyclerView)activity.findViewById(R.id.recyclerView);
layoutManager = new LinearLayoutManager(ctx);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(true);
adapter = new RecyclerAdapter(arrayList);
recyclerView.setAdapter(adapter);
}
#Override
public Void doInBackground(Void... params) {
try {
URL url = new URL(json_string);
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line=bufferedReader.readLine())!=null) {
stringBuilder.append(line+"\n");
}
httpURLConnection.disconnect();
String json_string = stringBuilder.toString().trim();
JSONObject jsonObject = new JSONObject(json_string);
JSONArray jsonArray = jsonObject.getJSONArray("server_response");
int count = 0;
while(count<jsonArray.length()){
JSONObject JO = jsonArray.getJSONObject(count);
count++;
Post post = new Post(JO.getString("headline"),JO.getString("source"),JO.getString("url"));
publishProgress(post);
}
Log.d("JSON STRING",json_string);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
public void onProgressUpdate(Post... values) {
arrayList.add(values[0]);
adapter.notifyDataSetChanged();
}
And my RecyclerAdapter
public class RecyclerAdapter extends RecyclerView.Adapter {
private static final int TYPE_HEAD = 0;
private static final int TYPE_LIST = 1;
ArrayList<Post> arrayList = new ArrayList<>();
public RecyclerAdapter (ArrayList<Post> arrayList){
this.arrayList = arrayList;
}
#Override
public RecyclerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if(viewType == TYPE_HEAD){
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_recycler,parent,false); // instead of row_recycler ,header_layout.
RecyclerViewHolder recyclerViewHolder = new RecyclerViewHolder(view,viewType);
return recyclerViewHolder;
}
if(viewType == TYPE_LIST){
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_recycler,parent,false);
RecyclerViewHolder recyclerViewHolder = new RecyclerViewHolder(view,viewType);
return recyclerViewHolder;
}
return null;
}
#Override
public void onBindViewHolder(RecyclerViewHolder holder, int position) {
if(holder.viewType == TYPE_LIST) {
Post post = arrayList.get(position-1);
holder.Headline.setText(post.getHeadline());
holder.Source.setText(post.getSource());
//holder.Url.setText(post.getUrl());
}
}
#Override
public int getItemCount() {
return arrayList.size()+1;
}
public static class RecyclerViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
TextView Headline,Source;//,Url;
int viewType;
public RecyclerViewHolder(View view,int viewType){
super(view);
if(viewType == TYPE_LIST) {
Headline = (TextView) view.findViewById(R.id.headline);
Source = (TextView) view.findViewById(R.id.source);
Headline.setOnClickListener(this);
Source.setOnClickListener(this);
// Url = (TextView) view.findViewById(R.id.url);
this.viewType = TYPE_LIST;
}else if (viewType == TYPE_HEAD){
this.viewType = TYPE_HEAD;
}
}
#Override
public void onClick(View v) {
Toast.makeText(v.getContext(), "ITEM PRESSED = " + String.valueOf(getAdapterPosition()), Toast.LENGTH_SHORT).show();
}
}
#Override
public int getItemViewType(int position){
if(position==0)
return TYPE_HEAD;
return TYPE_LIST;
}
public void setFilter(ArrayList<Post> newList){
arrayList = new ArrayList<>();
arrayList.addAll(newList);
notifyDataSetChanged();
}
}
Maybe that helps. i already set up a simple onclicklistener with a toast btw
I want to change the back ground of my list view row if the column value is same the the list view back ground would be change here is my code.
public class FillList extends AsyncTask<String, String, String> {
String z = "";
List<Map<String, String>> prolist = new ArrayList<Map<String, String>>();
#Override
protected void onPreExecute() {
}
#Override
protected void onPostExecute(String r) {
Toast.makeText(getActivity(), r, Toast.LENGTH_SHORT).show();
String[] from = {"C", "D", "E"};
int[] views = {R.id.accname, R.id.openingbalance, R.id.closingblanace};
final SimpleAdapter ADA = new SimpleAdapter(getActivity(),
prolist, R.layout.reportlayout, from,
views);
lstpro.setAdapter(ADA);
}
#Override
protected String doInBackground(String... params) {
try {
Connection con = connectionClass.CONN();
if (con == null) {
z = "Error in connection with SQL server";
} else {
final String stringlevel = getArguments().getString("level");
String query = "select * from GLSCOADetail where AccLevelNo<='"+ stringlevel +"'";
PreparedStatement ps = con.prepareStatement(query);
ResultSet rs = ps.executeQuery();
ArrayList<String> data1 = new ArrayList<String>();
while (rs.next()) {
Map<String, String> datanum = new HashMap<String, String>();
datanum.put("C", rs.getString("AccName"));
datanum.put("D", rs.getString("OpeningBalance"));
datanum.put("E", rs.getString("ClosingBalance"));
prolist.add(datanum);
}
z = "Success";
}
} catch (Exception ex) {
z = ex.getMessage();
}
return z;
}
}
I want to change my list view background on database filed if my database field match with list view then color of row would change please help me out.
Main (Activity)
public class Main extends Activity
{
private CustomAdapter adapter;
public ListView mListView = null;
public ArrayList<ListModel> CustomListViewValuesArr = new ArrayList<ListModel>();
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.listview_layout);
mListView = (ListView) findViewById(R.id.list);
setListData();
adapter = new CustomAdapter(this, CustomListViewValuesArr);
mListView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
/****** Function to set data in ArrayList *************/
public void setListData()
{
CustomListViewValuesArr.add(new ListModel("No1"));
CustomListViewValuesArr.add(new ListModel("No2"));//same
CustomListViewValuesArr.add(new ListModel("No3"));
CustomListViewValuesArr.add(new ListModel("No4"));
CustomListViewValuesArr.add(new ListModel("No2"));//same
}
}
listview_layout.xml (Activity xml)
<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" >
<ListView
android:id="#+id/list"
android:layout_width="fill_parent"
android:layout_height="match_parent"/>
</RelativeLayout>
CustomAdapter (Adapter)
public class CustomAdapter extends BaseAdapter
{
/*********** Declare Used Variables *********/
private Activity mActivity;
private ArrayList<ListModel> mList;
private static LayoutInflater mInflater = null;
private ListModel tempValues = null;
private int i=0;
/************* CustomAdapter Constructor *****************/
public CustomAdapter(Activity a, ArrayList d) {
/********** Take passed values **********/
mActivity = a;
mList = d;
/*********** Layout inflator to call external xml layout () ***********/
mInflater = ( LayoutInflater ) mActivity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
/******** What is the size of Passed Arraylist Size ************/
public int getCount() {
if(mList.size()<=0)
return 1;
return mList.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
/********* Create a holder Class to contain inflated xml file elements *********/
public static class ViewHolder
{
public TextView text;
}
/****** Depends upon mList size called for each row , Create each ListView row *****/
public View getView(int position, View convertView, ViewGroup parent)
{
View vi = convertView;
ViewHolder holder;
if(convertView==null){
/****** Inflate tabitem.xml file for each row ( Defined below ) *******/
vi = mInflater.inflate(R.layout.tabitem, null);
/****** View Holder Object to contain tabitem.xml file elements ******/
holder = new ViewHolder();
holder.text = (TextView) vi.findViewById(R.id.textView);
/************ Set holder with LayoutInflater ************/
vi.setTag( holder );
}
else
holder=(ViewHolder)vi.getTag();
if(mList.size() <= 0)
{
holder.text.setText("No Data");
}
else
{
tempValues = null;
tempValues = ( ListModel ) mList.get( position );
holder.text.setText( tempValues.getName() );
}
if(isDuplicate(tempValues.getName()))// this Method to check duplicate.
{
// Set a background color for ListView regular row/item
vi.setBackgroundColor(Color.parseColor("#FFB6B546"));
}
else
{
// Set the background color for alternate row/item
vi.setBackgroundColor(Color.parseColor("#FFCCCB4C"));
}
return vi;
}
private boolean isDuplicate(String item)
{
int count = 0;
for (int i = 0; i < mList.size(); i++)
{
ListModel listModel = mList.get(i);
if(item.equals(listModel.getName()))
count++;
}
if(count > 1)
return true;
else
return false;
}
}
ListModel (Model Class)
public class ListModel {
private String name ="";
/*********** Set Methods ******************/
public ListModel(String name)
{
this.name = name;
}
public void setName(String CompanyName)
{
this.name = CompanyName;
}
/*********** Get Methods ****************/
public String getName()
{
return this.name;
}
}
tabitem (ListView Adapter xml)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:text="TextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="10dp"
android:id="#+id/textView" />
</LinearLayout>
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 have Navigation Drawer with Fragment.
I set custom ListView from URL In Fragment.
But when I am running this, Items in ListView are not showing .
Data shows in log cat as well. i donot get any error on logcat
Fragment:
public class HomeFragment extends Fragment {
JSONArray post = null;
private ArrayList<HashMap<String, String>> PostList = new ArrayList<HashMap<String, String>>();
private View rootView;
private ListView list;
private StringRequest sr;
private RequestQueue queue;
private JSONArray laporanListObj;
private int Jumlah_list_Data;
private Adapter_Post adapter;
private Animation animstatuskoneksi;
private TextView statusKoneksi;
private ImageView nodata;
private ProgressBar load;
private Handler handler;
public HomeFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_home, container, false);
// adapter list
adapter = new Adapter_Post(getActivity(), PostList);
// animasi
animstatuskoneksi = AnimationUtils.loadAnimation(getActivity(),
R.anim.anim_status_koneksi);
// View Declare
list = (ListView) rootView.findViewById(android.R.id.list);
statusKoneksi = (TextView) rootView.findViewById(R.id.status_koneksi);
nodata = (ImageView) rootView.findViewById(R.id.NoData);
load = (ProgressBar) rootView.findViewById(R.id.load);
// set adapter
list.setAdapter(adapter);
// Listview on item click listener
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
TextView judul = (TextView) view.findViewById(R.id.judul);
TextView waktu_post = (TextView) view
.findViewById(R.id.waktu_post);
TextView id_post = (TextView) view.findViewById(R.id.id_post);
TextView link_detail_post = (TextView) view
.findViewById(R.id.link_detail_post);
String var_judul = judul.getText().toString();
String var_waktu_post = waktu_post.getText().toString();
String var_id_post = id_post.getText().toString();
String var_link_detail_post = link_detail_post.getText()
.toString();
// Starting single contact activity
// Intent in = new Intent(getActivity(), DetailActivity.class);
// in.putExtra(Variabel.KEY_JUDUL, var_judul);
// in.putExtra(Variabel.KEY_WAKTU_POST, var_waktu_post);
// in.putExtra(Variabel.KEY_ID_POST, var_id_post);
// in.putExtra(Variabel.KEY_LINK_DETAIL_POST,
// var_link_detail_post);
// startActivity(in);
Toast.makeText(getActivity(), "oke", Toast.LENGTH_LONG).show();
}
});
// Calling async task to get json
GetDataPost(Variabel.url_post);
return rootView;
}
public void GetDataPost(String url) {
if (queue != null) {
queue.cancelAll(sr);
}
// adapter.delete_all();
load.setVisibility(View.VISIBLE);
Log.v("Get Data", url);
queue = Volley.newRequestQueue(getActivity());
sr = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.v("hasil", response);
load.setVisibility(View.GONE);
DrawData(response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if (error instanceof NetworkError) {
statusKoneksi("Koneksi bermasalah");
} else if (error instanceof ServerError) {
statusKoneksi("Server Error");
} else if (error instanceof AuthFailureError) {
statusKoneksi("Koneksi Timeout");
} else if (error instanceof ParseError) {
statusKoneksi("Ada masalah dalam mengambil data");
} else if (error instanceof NoConnectionError) {
statusKoneksi("Tidak ada koneksi");
} else if (error instanceof TimeoutError) {
statusKoneksi("Koneksi Timeout");
}
load.setVisibility(View.GONE);
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> jsonParams = new HashMap<String, String>();
jsonParams.put("tag", Variabel.tag_default);
return jsonParams;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("Content-Type", "application/x-www-form-urlencoded");
return params;
}
};
queue.add(sr);
}
protected void DrawData(String response) {
JSONObject json = null;
try {
json = new JSONObject(response);
String res = json.getString(Variabel.KEY_SUCCESS);
String msg_err = json.getString(Variabel.KEY_ERROR_MSG);
if (Integer.parseInt(res) == 1) {
laporanListObj = json.getJSONArray(Variabel.KEY_POST);
Jumlah_list_Data = laporanListObj.length();
if (Jumlah_list_Data > 0) {
// count_data.setText(Jumlah_list_Data+" Data");
list.setVisibility(View.VISIBLE);
nodata.setVisibility(View.GONE);
for (int i = 0; i < Jumlah_list_Data; i++) {
JSONObject c = laporanListObj.getJSONObject(i);
// Storing each json item in variable
Variabel.judul_post = c.getString(Variabel.KEY_JUDUL);
Variabel.waktu_post = c
.getString(Variabel.KEY_WAKTU_POST);
Variabel.id_post = c.getString(Variabel.KEY_ID_POST);
Variabel.link_detail_post = c
.getString(Variabel.KEY_LINK_DETAIL_POST);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(Variabel.KEY_JUDUL, Variabel.judul_post);
map.put(Variabel.KEY_WAKTU_POST, Variabel.waktu_post);
map.put(Variabel.KEY_ID_POST, Variabel.id_post);
map.put(Variabel.KEY_LINK_DETAIL_POST,
Variabel.link_detail_post);
// adding HashList to ArrayList
PostList.add(map);
}
adapter.notifyDataSetChanged();
}
} else {
list.setVisibility(View.GONE);
nodata.setVisibility(View.VISIBLE);
statusKoneksi(msg_err);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Listview Adapter:
public class Adapter_Post extends BaseAdapter {
private Activity activity;
private ArrayList<HashMap<String, String>> data;
private ImageLoaderDetailImage ImageLoader;
private int loader;
private static LayoutInflater inflater = null;
public Adapter_Post(Activity a, ArrayList<HashMap<String, String>> d) {
activity = a;
data = d;
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
ImageLoader = new ImageLoaderDetailImage(activity.getBaseContext());
loader = R.drawable.ic_drawer;
}
public int getCount() {
return data.size();
}
public void delete_all() {
int count = getCount();
if (count > 0) {
data.clear();
notifyDataSetChanged();
}
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
/* private view holder class */
private class ViewHolder {
public TextView judul;
public TextView waktu_post;
public TextView id_post;
public TextView link_detail_post;
// public RoundedImageView foto_bus;
}
public View getView(final int position, View convertView, ViewGroup parent) {
View vi = convertView;
final ViewHolder holder;
if (convertView == null) {
vi = inflater.from(activity)
.inflate(R.layout.list_item, null, true);
holder = new ViewHolder();
// holder.foto_bus =
// (RoundedImageView)vi.findViewById(R.id.foto_bus);
holder.judul = (TextView) vi.findViewById(R.id.judul);
holder.waktu_post = (TextView) vi.findViewById(R.id.waktu_post);
holder.id_post = (TextView) vi.findViewById(R.id.id_post);
holder.link_detail_post = (TextView) vi
.findViewById(R.id.link_detail_post);
vi.setTag(holder);
} else {
holder = (ViewHolder) vi.getTag();
}
HashMap<String, String> kendaraan = new HashMap<String, String>();
kendaraan = data.get(position);
// set data
holder.judul.setText(kendaraan.get(Variabel.KEY_JUDUL));
holder.waktu_post.setText(kendaraan.get(Variabel.KEY_WAKTU_POST));
holder.id_post.setText(kendaraan.get(Variabel.KEY_ID_POST));
holder.link_detail_post.setText(kendaraan
.get(Variabel.KEY_LINK_DETAIL_POST));
// ImageLoader.DisplayImage(kendaraan.get(Variabel.KEY_FOTO_BUS),loader,
// holder.foto_bus);
return vi;
}
}
UPDATED
Fragment XML
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#null"
android:cacheColorHint="#android:color/transparent"
android:divider="#android:color/transparent"
android:dividerHeight="1px"
android:listSelector="#null"
android:visibility="visible" >
</ListView>
<ProgressBar
android:id="#+id/load"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true" />
<ImageView
android:id="#+id/NoData"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:background="#null"
android:src="#drawable/nodata"
android:visibility="visible" />
<TextView
android:id="#+id/status_koneksi"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:background="#99000000"
android:gravity="center"
android:padding="8dp"
android:text="msg."
android:textColor="#ffffff"
android:visibility="visible" />
</RelativeLayout>
any mistake in my code ?
How to fix it ?
sorry for my english .. thanks
you should change this
list=(ListView)rootView.findViewById(android.R.id.list);
to
list=(ListView)rootView.findViewById(R.id.list);
and make sure you have ListView with id list in your fragment_home layout.
In getview method of adapter change the parameters of this:
vi = inflater.from(activity).inflate(R.layout.list_item, null, true);
to:
vi = inflater.from(activity).inflate(R.layout.list_item, parent, false);