I have created a listview. All values are retrieved from the json response but only the last values were displayed in the list.what to do for displaying the all values in list view.
SixFragment.movieList = new ArrayList<Movie1>();
for (int i1 = 0; i1 < jsonArray3.length(); i1++) {
try {
JSONObject jsonObject = jsonArray3.getJSONObject(i1);
review_rating = jsonObject.optString("review_rating").toString();
username_rate = jsonObject.optString("username").toString();
review_title = jsonObject.optString("review_title").toString();
review_desc = jsonObject.optString("review_desc").toString();
sleep = jsonObject.optString("Sleep").toString();
location = jsonObject.optString("Location").toString();
service = jsonObject.optString("Service").toString();
rooms = jsonObject.optString("Rooms").toString();
cleanliness = jsonObject.optString("Cleanliness").toString();
userimage1 = jsonObject.optString("user_image").toString();
Movie1 movie = new Movie1();
movie.setRate_userimage(userimage1);
movie.setreview_rating(review_rating);
movie.setusername_rate(username_rate);
movie.setreview_title(review_title);
movie.setreview_desc(review_desc);
movie.setsleep(sleep);
movie.setlocation(location);
movie.setservice(service);
movie.setraterooms(rooms);
movie.setcleanliness(cleanliness);
SixFragment.movieList.add(movie);
} catch (JSONException e) {
e.printStackTrace();
}
}
This is my fragment page:
public class SixFragment extends Fragment{
public static String userimage;
public static String review_rating;
public static String username_rate;
public static String review_title;
public static String review_desc;
public static String sleep;
public static String location;
public static String service;
public static String rooms;
public static String cleanliness;
public static ArrayList stringArray;
public static ArrayList<Movie1> movieList= new ArrayList<Movie1>();;
ListView listView;
Reviewadapter reviewadapter;
public SixFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v= inflater.inflate(R.layout.fragment_six, container, false);
ListView list=(ListView)v.findViewById(R.id.six_listView);
return v;
}
}
This logcat error`
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.airstar.abservetech.airstar, PID: 27390
java.lang.NullPointerException
at com.airstar.abservetech.adapter.Reviewadapter.getCount(Reviewadapter.java:160)
at android.widget.ListView.setAdapter(ListView.java:488)
at com.airstar.abservetech.airstar.SixFragment.onCreateView(SixFragment.java:75)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:1974)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1067)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1252)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:742)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1617)
at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:570)
at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:141)
`
Review adapter
public class Reviewadapter extends BaseAdapter {
private final List<Movie1> movieItems;
public SixFragment context;
OneFragment Fragment;
Bitmap bitmap;
public Reviewadapter(SixFragment context, List<Movie1> movieItems) {
this.context = context;
this.movieItems = movieItems;
this.Fragment=Fragment;
}
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
convertView = inflater.inflate(R.layout.fragment_sixlist,parent,false);
CircleImageView profile_image = (CircleImageView) convertView.findViewById(R.id.profile_image);
TextView rate_username = (TextView) convertView.findViewById(R.id.rate_username);
RatingBar ratingBar = (RatingBar) convertView.findViewById(R.id.ratingBar);
TextView rate_title = (TextView) convertView.findViewById(R.id.rate_title);
TextView rate_description = (TextView) convertView.findViewById(R.id.rate_description);
RatingBar ratingBar_sleep = (RatingBar) convertView.findViewById(R.id.ratingBar_sleep);
RatingBar ratingBar_location = (RatingBar) convertView.findViewById(R.id.ratingBar_location);
RatingBar ratingBar_service = (RatingBar) convertView.findViewById(R.id.ratingBar_service);
RatingBar ratingBar_clearness = (RatingBar) convertView.findViewById(R.id.ratingBar_clearness);
RatingBar ratingBar_rooms = (RatingBar) convertView.findViewById(R.id.ratingBar_rooms);
final Movie1 m = movieItems.get(position);
// Glide.with(context)
// .load(m.getRate_userimage())
// .diskCacheStrategy(DiskCacheStrategy.ALL)
// .into(profile_image);
URL url = null;
String image=m.getRate_userimage();
try {
url = new URL(image);
InputStream is = null;
// Bitmap bitMap = BitmapFactory.decodeStream(is);
//create imageview dynamically
Glide.with(context).load(String.valueOf(url)).into(profile_image);
} catch (MalformedURLException e) {
e.printStackTrace();
}
//Glide.with(context).load(String.valueOf(url)).into(profile_image);
if (m.getusername_rate()!=null)
{
if (!m.getusername_rate().equals("null"))
{
rate_username.setText(m.getusername_rate());
}}
if (m.getreview_rating()!=null)
{
if (!m.getreview_rating().equals("null"))
{
ratingBar.setRating(Float.parseFloat(m.getreview_rating()));
}}
if (m.getsleep()!=null)
{
if (!m.getsleep().equals("null"))
{
ratingBar_sleep.setRating(Float.parseFloat(m.getsleep()));
}}
}
return convertView;
}
#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;
}
}
In Your Fragment make your list static:
public class SixFragment extends Fragment{
// Your code
//------------DO THIS------------------///
public static List<Movie1> movieList = new ArrayList<Movie1>();
public SixFragment() {
// Required empty public constructor
}
//Your code
}
Rest of the code in your fragment will be as it is.
Change your JSON loop like this :
SixFragment.movieList = new ArrayList<Movie1>();
for (int i1 = 0; i1 < jsonArray3.length(); i1++) {
try {
JSONObject jsonObject = jsonArray3.getJSONObject(i1);
review_rating = jsonObject.optString("review_rating").toString();
username_rate = jsonObject.optString("username").toString();
review_title = jsonObject.optString("review_title").toString();
review_desc = jsonObject.optString("review_desc").toString();
sleep = jsonObject.optString("Sleep").toString();
location = jsonObject.optString("Location").toString();
service = jsonObject.optString("Service").toString();
rooms = jsonObject.optString("Rooms").toString();
cleanliness = jsonObject.optString("Cleanliness").toString();
userimage1 = jsonObject.optString("user_image").toString();
Movie1 movie = new Movie1();
movie.setRate_userimage(userimage1);
movie.setreview_rating(review_rating);
movie.setusername_rate(username_rate);
movie.setreview_title(review_title);
movie.setreview_desc(review_desc);
movie.setsleep(sleep);
movie.setlocation(location);
movie.setservice(service);
movie.setraterooms(rooms);
movie.setcleanliness(cleanliness);
SixFragment.movieList.add(movie);
} catch (JSONException e) {
e.printStackTrace();
}
}
Related
I am trying to fetch a text and image link from the database and add it to an ArrayList and then use it to display the text and image in a grid view. But it doesn't show up. It seems like the list items seem to be null when I try to add it.
What am I missing? I have gone through some answers and wasn't able to figure it out.
public final class GridAdapter extends BaseAdapter {
public static final String showUrl = "http://netbigs.com/apps/fetch.php";
String myJSON;
public String mvname;
String mvinfo;
public String rdate,imglink;
private Context mContext;
private final List<Item> mItems = new ArrayList<Item>();
private final LayoutInflater mInflater;
private static final String TAG_RESULTS = "result";
private static final String TAG_ID = "mvid";
private static final String TAG_NAME = "mvname";
private static final String TAG_IMG = "imglink";
private static final String TAG_DATE = "rdate";
private static final String TAG_MOVINF = "mvinfo";
JSONArray movies = null;
public GridAdapter(Context context) {
mItems.add(new Item(mvname,imglink));
mContext=context;
mInflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return mItems.size();
}
#Override
public Item getItem(int i) {
return mItems.get(i);
}
#Override
public long getItemId(int i) {
return 0;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
View v = view;
ImageView picture;
TextView name;
getData();
if (v == null) {
v = mInflater.inflate(R.layout.grid_item, viewGroup, false);
v.setTag(R.id.picture, v.findViewById(R.id.picture));
v.setTag(R.id.text, v.findViewById(R.id.text));
}
picture = (ImageView) v.getTag(R.id.picture);
name = (TextView) v.getTag(R.id.text);
Item item = getItem(i);
Picasso.with(this.mContext).load(item.drawableId).into(picture);
name.setText(item.name);
System.out.println(item.name);
return v;
}
private static class Item {
public final String name;
public final String drawableId;
Item(String name, String drawableId) {
this.name = name;
this.drawableId = drawableId;
}
}
protected void showList(){
try{
JSONObject jsonObj = new JSONObject(myJSON);
movies = jsonObj.getJSONArray(TAG_RESULTS);
for (int i=0;i<movies.length();i++){
JSONObject c = movies.getJSONObject(i);
String mvid = c.getString(TAG_ID);
mvname = c.getString(TAG_NAME);
System.out.println(mvname);
imglink = c.getString(TAG_IMG);
System.out.println(imglink);
rdate = c.getString(TAG_DATE);
mvinfo = c.getString(TAG_MOVINF);
try {
}
catch (Exception e){
e.printStackTrace();
}
}
}
catch (JSONException e){
e.printStackTrace();
}
}
public void getData(){
class GetDataJSON extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
try {
String uri = showUrl;
URL url = new URL(uri);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
InputStream inputStream = null;
String result = null;
inputStream = con.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
return sb.toString();
} catch (Exception e) {
return null;
}
}
#Override
protected void onPostExecute(String result){
myJSON=result;
showList();
}
}
GetDataJSON g = new GetDataJSON();
g.execute();
}
}
This is the fragment to which the GridAdapter is attached.
public class MovieFragment extends Fragment {
public MovieFragment() {
// Required empty public constructor
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, final ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_movie, container, false);
GridView gridView = (GridView)view.findViewById(R.id.gridview);
gridView.setAdapter(new GridAdapter(getActivity()));
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent i;
switch (position){
case 0:
i = new Intent(MovieFragment.this.getActivity(),MovieDetail.class);
startActivity(i);
break;
case 1:
i = new Intent(MovieFragment.this.getActivity(),MovieDetail.class);
startActivity(i);
break;
case 2:
i = new Intent(MovieFragment.this.getActivity(),MovieDetail.class);
startActivity(i);
break;
case 3:
i = new Intent(MovieFragment.this.getActivity(),MovieDetail.class);
startActivity(i);
break;
}
}
});
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
public void onDetach() {
super.onDetach();
}
}
You are calling getData() from your Adapter so it may possible that when you initialize it at that time your list is null.
Try calling that method form your activity or fragment and then pass the received data you received in your adapter class.
getView() is called multiple time when you scroll up or down so never call any api in that method
Provide the code where you are using this adapter.
the problem is you are not getting values from the DB.
you must get the values from the db first. by using Volley or some plugin like that(or Aysnc task. volley will be better i think.)
I have problem while diplayin pictures , nothing is dsplayed in the sceen , seems empty only data are displayed no pictures. I think that the problem while parsing JSON Data in pictures.
here in the Fragment of the hotel where i want to display picture gallery.
public class ViewHotels extends AppCompatActivity {
private Bitmap bitmap;
private TextView nom1;
private TextView grade;
private TextView tele;
private ImageView image;
private TextView sit;
private TextView add1;
private TextView email1;
private FloatingActionButton fab;
LinearLayout layout;
private String id;
public static final String URL="http://gabes.comlu.com/Base_Controle/getEmpdetail.php";
private FeatureCoverFlow coverFlow;
private CoverFlowAdapter adapter;
private ArrayList<Game> games;
String image2;
String addresses;
String subject;
public static final String TAG_JSON_ARRAY="result";
ImageView im;
private int imageSource;
public String stringUrl;
public String stringUrl1;
public String stringUrl2;
public String stringUrl3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.hotelsdetails);
final Intent intent = getIntent();
layout=(LinearLayout) findViewById(R.id.layout);
coverFlow = (FeatureCoverFlow) findViewById(R.id.coverflow);
settingDummyData();
adapter = new CoverFlowAdapter(this, games);
coverFlow.setAdapter(adapter);
coverFlow.setOnScrollPositionListener(onScrollListener());
id = intent.getStringExtra("Type");
nom1 = (TextView) findViewById(R.id. nom);
grade = (TextView) findViewById(R.id. grade);
tele = (TextView) findViewById(R.id. tele);
image= (ImageView)findViewById(R.id.imageView);
sit=(TextView) findViewById(R.id.site);
add1=(TextView) findViewById(R.id.adde);
email1=(TextView)findViewById(R.id.email);
nom1.setText(id);
im =new ImageView (this);
getEmployee();
}
private void getEmployee(){
final String login11 = nom1.getText().toString().trim();
class GetEmployee extends AsyncTask<Void,Void,String>{
ProgressDialog loading;
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(ViewHotels.this,"Fetching...","Wait...",false,false);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
showEmployee(s);
}
#Override
protected String doInBackground(Void... v) {
HashMap<String,String> params = new HashMap<>();
params.put("id",login11)
RequestHandler rh = new RequestHandler();
String res= rh.sendPostRequest(URL, params);
return res;
}
}
GetEmployee ge = new GetEmployee();
ge.execute();
}
private void showEmployee(String json){
try {
JSONArray result = new JSONArray(json);
JSONObject c = result.getJSONObject(0);
String name = c.getString("nom");
String tel = c.getString("tele");
String grade1 = c.getString("grade");
String image1 = c.getString("image");
image2 = c.getString("img1");
String image3 = c.getString("img2");
String image4 = c.getString("img3");
String site= c.getString("site");
String add11= c.getString("add");
String email11= c.getString("email");
tele.setText("Tel : \t"+tel);
grade.setText("Grade : \t"+grade1);
sit.setText("site: \t"+site);
add1.setText("adresse :\t" + add11);
email1.setText("email :\t"+ email11);
final ImageView im1 =new ImageView (this);
final ImageView im2 =new ImageView (this);
final ImageView im3 =new ImageView (this);
stringUrl = ("http://gabes.comlu.com/Base_Controle/ImageBD/"+image1+".jpg");
stringUrl1 = ("http://gabes.comlu.com/Base_Controle/ImageBD/"+image2+".jpg");
stringUrl2 = ("http://gabes.comlu.com/Base_Controle/ImageBD/"+image3+".jpg");
stringUrl3 = ("http://gabes.comlu.com/Base_Controle/ImageBD/"+image4+".jpg");
} catch (JSONException e) {
e.printStackTrace();
}
}
private FeatureCoverFlow.OnScrollPositionListener onScrollListener() {
return new FeatureCoverFlow.OnScrollPositionListener() {
#Override
public void onScrolledToPosition(int position) {
Log.v("ViewHotels", "position: " + position);
}
#Override
public void onScrolling() {
Log.i("ViewHotels", "scrolling");
}
};
}
private void settingDummyData() {
games = new ArrayList<>();
Game game1 = new Game("stringUrl","");
Game game2 = new Game("stringUrl1","");
Game game3 = new Game("stringUrl2","");
games.add(game1);
games.add(game2);
games.add(game3);
}
}
Here is the coverFlow adapter :
public class CoverFlowAdapter extends BaseAdapter {
private ArrayList<Game> data;
private AppCompatActivity activity;
public CoverFlowAdapter(AppCompatActivity context, ArrayList<Game> objects) {
this.activity = context;
this.data = objects;
}
#Override
public int getCount() {
return data.size();
}
#Override
public Game getItem(int position) {
return data.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder;
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.item_flow_view, null, false);
viewHolder = new ViewHolder(convertView);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
try {
URL myFileUrl = new URL(data.get(position).getImageSource());
Log.e("TAG stringUri",myFileUrl+"" );
HttpURLConnection conn = (HttpURLConnection) myFileUrl.openConnection();
conn.setDoInput(true);
conn.connect();
InputStream is = conn.getInputStream();
viewHolder.gameImage.setImageBitmap(BitmapFactory.decodeStream(is));
}
catch (MalformedURLException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
//viewHolder.gameImage.setImageResource(data.get(position).getImageSource());
viewHolder.gameName.setText(data.get(position).getName());
return convertView;
}
private static class ViewHolder {
private TextView gameName;
private ImageView gameImage;
public ViewHolder(View v) {
gameImage = (ImageView) v.findViewById(R.id.image);
gameName = (TextView) v.findViewById(R.id.name);
}
}
}
And this the Game class :
public class Game {
private String name;
private String imageSource;
public Game (String imageSource, String name) {
this.name = name;
this.imageSource = imageSource;
}
public String getName() {
return name;
}
public String getImageSource() {
return imageSource;
}
}
I think (one of) your problem(s) is this part:
Game game1 = new Game("stringUrl","");
Game game2 = new Game("stringUrl1","");
Game game3 = new Game("stringUrl2","");
You are handing over the String "stringUrlx" to your Game-constructor.
In Java, quotation marks("") are used to explicitly define a string, which means that you are handing over "stringUrl" instead of the variable stringUrl, which would have the correct content ("http://gabes.comlu.com/Base_Controle/ImageBD/"+image1+".jpg").
so replace e.g.
Game game1 = new Game("stringUrl","");
by
Game game1 = new Game(stringUrl,"");
That should solve that one issue.
Other than that, you will also run into issues downloading your files and with memory management. I advise you to look into java specific tutorials, which use pre-built asynchronous image loading and caching libraries (such as Glide or Picasso !)
I have some problem. when I click a delete(btnPlus.setOnClickListener in the interestAdepter class) button from listview baseAdapter, I want to refresh the fragment which contains the listview.
1.InterestAdapter class{edtied}
public class InterestAdapter extends BaseAdapter{
private ArrayList<InterestClass> m_List;
public InterestAdapter() {
m_List = new ArrayList<InterestClass>();
}
#Override
public int getCount() {
return m_List.size();
}
#Override
public Object getItem(int position) {
return m_List.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final int pos = position;
final Context context = parent.getContext();
TextView textName = null;
TextView textDate = null;
TextView textConPrice = null;
TextView textNowPrice = null;
TextView textFog = null;
ImageButton btnPlus = null;
CustomHolder holder = null;
if ( convertView == null ) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.item_interest, parent, false);
textName = (TextView) convertView.findViewById(R.id.i_ProdNmae);
textDate = (TextView) convertView.findViewById(R.id.i_Date);
textConPrice = (TextView) convertView.findViewById(R.id.i_InterPrice);
textNowPrice = (TextView) convertView.findViewById(R.id.i_currentPrice);
textFog = (TextView) convertView.findViewById(R.id.i_Analysis);
btnPlus = (ImageButton) convertView.findViewById(R.id.i_addBtn);
holder = new CustomHolder();
holder.i_TextView = textName;
holder.i_TextView1 = textDate;
holder.i_TextView2 = textConPrice;
holder.i_TextView3 = textNowPrice;
holder.i_TextView4 = textFog;
holder.i_Btn = btnPlus;
convertView.setTag(holder);
}
else {
holder = (CustomHolder) convertView.getTag();
textName = holder.i_TextView;
textDate = holder.i_TextView1;
textConPrice = holder.i_TextView2;
textNowPrice = holder.i_TextView3;
textFog = holder.i_TextView4;
btnPlus = holder.i_Btn;
}
/*if(position == 0) {
textName.setText("종목");
textDate.setText("관심일");
textConPrice.setText("관심가");
textNowPrice.setText("현재가");
textFog.setText("수급");
btnPlus.setEnabled(false);
}else{
}*/
textName.setText(m_List.get(position).getName());
textDate.setText(m_List.get(position).getDate());
textConPrice.setText(m_List.get(position).getConPrice());
textNowPrice.setText(m_List.get(position).getNowPrice());
textFog.setText(m_List.get(position).getFog());
btnPlus.setEnabled(true);
textName.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context,DetailActivity.class);
context.startActivity(intent);
}
});
btnPlus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Crypto enc = new Crypto();
SharedPreferences pref = context.getSharedPreferences("com.rabiaband.pref", 0);
String[] add_Params = new String[2];
try {
add_Params[0] = enc.AES_Encode(pref.getString("no", null), enc.global_deckey);
add_Params[1] = enc.AES_Encode(m_List.get(pos).getJmcode(), enc.global_deckey);
} catch (Exception e) {
Log.e("HomeCryptographError:", "" + e.getMessage());
}
AsyncCallAddDelFavorite delFavorite = new AsyncCallAddDelFavorite();
delFavorite.execute(add_Params);
}
});
private class AsyncCallAddDelFavorite extends AsyncTask<String, Void, Void> {
JSONObject del_Favorite_List;
/* public AsyncCallAddFavorite(HomeFragment home){
this.home=home;
}*/
#Override
protected void onPreExecute() {
/*Log.i(TAG, "onPreExecute");*/
}
#Override
protected Void doInBackground(String... params) {
dbConnection db_Cont=new dbConnection();
String id=params[0];
String jmcode=params[1];
Log.v("doinbackgroud",""+id+"ssssss"+jmcode);
del_Favorite_List=db_Cont.delFavorite(id, jmcode);
Log.v("doinbackgroud",del_Favorite_List.toString());
return null;
}
#Override
protected void onPostExecute(Void result) {
/*Log.i(TAG, "onPostExecute");*/
}
}
}
2.InterestFragment{edited}
public class InterestFragment extends Fragment {
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
private ListView interest_ListView;
private InterestAdapter interest_Adapter;
String TAG="response";
RbPreference keep_Login;
public InterestFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment InterestFragment.
*/
// TODO: Rename and change types and number of parameters
public static InterestFragment newInstance(String param1, String param2) {
InterestFragment fragment = new InterestFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
keep_Login = new RbPreference(getContext());
Log.v("interFrag","oncreate");
// Inflate the layout for this fragment
/*if(keep_Login.get("name",null)!=null) {
return inflater.inflate(R.layout.fragment_interest, container, false);
}else{
return inflater.inflate(R.layout.need_login, container, false);
}*/
return inflater.inflate(R.layout.fragment_interest, container, false);
}
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Log.v("ListFragment", "onActivityCreated().");
Log.v("ListsavedInstanceState", savedInstanceState == null ? "true" : "false");
if(keep_Login.get("no",null)!=null) {
String enc_Id="";
Crypto enc=new Crypto();
try{
enc_Id=enc.AES_Encode(keep_Login.get("no",null),enc.global_deckey);
}catch(Exception e){
}
interest_Adapter = new InterestAdapter();
interest_ListView = (ListView) getView().findViewById(R.id.i_ListView);
AsyncCallInterest task = new AsyncCallInterest();
task.execute(enc_Id);
}
}
private class AsyncCallInterest extends AsyncTask<String, Void, JSONArray> {
JSONArray interest_Array;
InterestFragment interest;
#Override
protected void onPreExecute() {
Log.i(TAG, "onPreExecute");
}
#Override
protected JSONArray doInBackground(String... params) {
String id=params[0];
dbConnection db_Cont=new dbConnection();
interest_Array=db_Cont.getFavorite(id);
Log.v("doinbackgroud", interest_Array.toString());
return interest_Array;
}
#Override
protected void onPostExecute(JSONArray result) {
try{
for (int i = 0 ; i < result.length() ; i ++){
InterestClass i_Class = new InterestClass();
String date=result.getJSONObject(i).getString("indate");
String time=date.substring(5,date.length());
i_Class.setJmcode(result.getJSONObject(i).getString("jmcode"));
i_Class.setName(result.getJSONObject(i).getString("jmname"));
i_Class.setDate(time);
i_Class.setConPrice(result.getJSONObject(i).getString("fprice"));
i_Class.setNowPrice(result.getJSONObject(i).getString("price"));
i_Class.setFog("40");
i_Class.setPlus(true);
interest_Adapter.add(i_Class);
}
interest_ListView.setAdapter(interest_Adapter);
}catch(Exception e){
Toast.makeText(getActivity(), "interest"+e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
}
}
Is there any way to refresh the fragment from the button in baseAdapter class? I searched a lot but I couldn't fine answer. Please help me, Thank you.
{edited}
I add AsyncCallAddDelFavorite class and AsyncCallInterest class. Thank you.
Update your adapter constructor. After deleting content, remove the item from the arraylist and notify dataset changed.
public class InterestAdapter extends BaseAdapter{
private ArrayList<InterestClass> m_List;
private Context mContext;
public InterestAdapter(Context context, ArrayList<InterestClass> list) {
m_List = list;
mContext = context;
}
#Override
public int getCount() {
return m_List.size();
}
#Override
public Object getItem(int position) {
return m_List.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final int pos = position;
final Context context = parent.getContext();
TextView textName = null;
TextView textDate = null;
TextView textConPrice = null;
TextView textNowPrice = null;
TextView textFog = null;
ImageButton btnPlus = null;
CustomHolder holder = null;
if ( convertView == null ) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.item_interest, parent, false);
textName = (TextView) convertView.findViewById(R.id.i_ProdNmae);
textDate = (TextView) convertView.findViewById(R.id.i_Date);
textConPrice = (TextView) convertView.findViewById(R.id.i_InterPrice);
textNowPrice = (TextView) convertView.findViewById(R.id.i_currentPrice);
textFog = (TextView) convertView.findViewById(R.id.i_Analysis);
btnPlus = (ImageButton) convertView.findViewById(R.id.i_addBtn);
holder = new CustomHolder();
holder.i_TextView = textName;
holder.i_TextView1 = textDate;
holder.i_TextView2 = textConPrice;
holder.i_TextView3 = textNowPrice;
holder.i_TextView4 = textFog;
holder.i_Btn = btnPlus;
convertView.setTag(holder);
}
else {
holder = (CustomHolder) convertView.getTag();
textName = holder.i_TextView;
textDate = holder.i_TextView1;
textConPrice = holder.i_TextView2;
textNowPrice = holder.i_TextView3;
textFog = holder.i_TextView4;
btnPlus = holder.i_Btn;
}
/*if(position == 0) {
textName.setText("종목");
textDate.setText("관심일");
textConPrice.setText("관심가");
textNowPrice.setText("현재가");
textFog.setText("수급");
btnPlus.setEnabled(false);
}else{
}*/
textName.setText(m_List.get(position).getName());
textDate.setText(m_List.get(position).getDate());
textConPrice.setText(m_List.get(position).getConPrice());
textNowPrice.setText(m_List.get(position).getNowPrice());
textFog.setText(m_List.get(position).getFog());
btnPlus.setEnabled(true);
textName.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context,DetailActivity.class);
context.startActivity(intent);
}
});
btnPlus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Crypto enc = new Crypto();
SharedPreferences pref = context.getSharedPreferences("com.rabiaband.pref", 0);
String[] add_Params = new String[2];
try {
add_Params[0] = enc.AES_Encode(pref.getString("no", null), enc.global_deckey);
add_Params[1] = enc.AES_Encode(m_List.get(pos).getJmcode(), enc.global_deckey);
} catch (Exception e) {
Log.e("HomeCryptographError:", "" + e.getMessage());
}
AsyncCallAddDelFavorite delFavorite = new AsyncCallAddDelFavorite();
delFavorite.execute(add_Params);
**m_List.remove(position);
notifyDatasetChanged();**
}
});
private class AsyncCallAddDelFavorite extends AsyncTask<String, Void, Void> {
JSONObject del_Favorite_List;
/* public AsyncCallAddFavorite(HomeFragment home){
this.home=home;
}*/
#Override
protected void onPreExecute() {
/*Log.i(TAG, "onPreExecute");*/
}
#Override
protected Void doInBackground(String... params) {
dbConnection db_Cont=new dbConnection();
String id=params[0];
String jmcode=params[1];
Log.v("doinbackgroud",""+id+"ssssss"+jmcode);
del_Favorite_List=db_Cont.delFavorite(id, jmcode);
Log.v("doinbackgroud",del_Favorite_List.toString());
return null;
}
#Override
protected void onPostExecute(Void result) {
/*Log.i(TAG, "onPostExecute");*/
}
}
}
Update Adapter initialization in fragment. You are adding item to adapter directly. Use arraylist and after downloading data create adapter instance.
private ArrayList<InterestClass> interestList = new ArrayList<>();
and update your onPostExecute Method
#Override
protected void onPostExecute(JSONArray result) {
try{
for (int i = 0 ; i < result.length() ; i ++){
InterestClass i_Class = new InterestClass();
String date=result.getJSONObject(i).getString("indate");
String time=date.substring(5,date.length());
i_Class.setJmcode(result.getJSONObject(i).getString("jmcode"));
i_Class.setName(result.getJSONObject(i).getString("jmname"));
i_Class.setDate(time);
i_Class.setConPrice(result.getJSONObject(i).getString("fprice"));
i_Class.setNowPrice(result.getJSONObject(i).getString("price"));
i_Class.setFog("40");
i_Class.setPlus(true);
interestList.add(i_Class);
}
interest_Adapter = new InterestAdapter(getActivity,interestList);
interest_ListView.setAdapter(interest_Adapter);
}catch(Exception e){
Toast.makeText(getActivity(), "interest"+e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
If I understand you correctly you want to remove the item from your ListView too after your removing it from your Database, to achieve that you can call this
m_List.remove(position);
interest_Adapter..notifyDataSetChanged();
First line removes the item and Second one will insure that the Adapter gets updated after the item has been removed.
Hope this helps
May be this question many times.
i am getting some data from server and showing in listview . every thing working fine but i am getting problem to show image in list view.
Here is my example code
public class MainActivity extends ListActivity {
private static String url = null;
private static final String book_name = "b_name";
private static final String book_detail = "b_publisher";
private static final String book_image = "b_image";
ProgressDialog progressDialog;
ListView lv;
String cus_id;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
}
url = getResources().getString(R.string.url);
/*----Receiving data from Splash Activity-----*/
Bundle b = getIntent().getExtras();
cus_id = b.getString("custom_id");
new ProgressTask(MainActivity.this).execute();
}
class ProgressTask extends AsyncTask<String, Integer, Boolean> {
ArrayList<HashMap<String, String>> jsonlist = new ArrayList<HashMap<String, String>>();
public ProgressTask(ListActivity activity) {
context = activity;
}
private Context context;
protected void onPreExecute() {
progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setTitle("Processing...");
progressDialog.setMessage("Please wait...");
progressDialog.setCancelable(false);
progressDialog.show();
}
#Override
protected void onProgressUpdate(Integer... values) {
// set the current progress of the progress dialog
progressDialog.setProgress(values[0]);
}
#Override
protected void onPostExecute(final Boolean success) {
progressDialog.dismiss();
}
protected Boolean doInBackground(final String... args) {
url = url + "?custom_iid=" + cus_id;
Log.d("Passing Url", url);
CustomListAdapter jParser = new CustomListAdapter();
JSONArray json = jParser.getJSONFromUrl(url);
if (json != null) {
for (int i = 0; i < json.length(); i++) {
try {
JSONObject c = json.getJSONObject(i);
String b_image = c.getString("b_image");
String b_name = c.getString("b_name");
String b_detail = c.getString("b_publisher");
Log.d("detail", "" + b_image);
setBookImageUrl(b_image);
setBookName(b_name);
setBookDetail(b_detail);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
return null;
}
public String getBookImageUrl() {
return book_image;
}
public CharSequence getBookName() {
return book_name;
}
public CharSequence getBookDetail() {
return book_detail;
}
public void setBookImageUrl(String imgeUrl) {
book_image = imgeUrl;
}
public void setBookName(String b_name) {
book_name = b_name;
}
public void setBookDetail(String b_detail) {
book_detail = b_detail;
}
}
BookListAdapter class:
public class BookListAdapter extends ArrayAdapter<MainActivity> {
private ArrayList<MainActivity> bookModels;
private Context context;
public BookListAdapter(Context context, int resource,
ArrayList<MainActivity> bookModels) {
super(context, resource, bookModels);
this.bookModels = bookModels;
this.context = context;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View rowView = convertView;
if (rowView == null) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
rowView = inflater.inflate(R.layout.row_list_item, null);
ViewHolder viewHolder = new ViewHolder();
viewHolder.bookIcon = (ImageView) rowView.findViewById(R.id.icon);
viewHolder.bookName = (TextView) rowView.findViewById(R.id.b_name);
viewHolder.bookDetail = (TextView) rowView
.findViewById(R.id.b_detail);
rowView.setTag(viewHolder);
}
final MainActivity bookModel = bookModels.get(position);
ViewHolder holder = (ViewHolder) rowView.getTag();
Picasso.with(context).load(bookModel.getBookImageUrl())
.into(holder.bookIcon);
holder.bookName.setText(bookModel.getBookName());
holder.bookDetail.setText(bookModel.getBookDetail());
return rowView;
}
#Override
public int getCount() {
return bookModels.size();
}
static class ViewHolder {
public ImageView bookIcon;
public TextView bookName;
public TextView bookDetail;
}
}
i can show book name and book detail in listview finely but image is not showing ..
i am getting value for book_image is http:\/\/X.X.X.X\/admin\/book_images\/232513pic9.png how to show in listview from that path..
I think you will need to implement your own adapter and use some library to display the image from URL.
My recommendation is Picasso
This is an example to implement your own adapter
BookListAdapter.java
public class BookListAdapter extends ArrayAdapter<BookModel> {
private ArrayList<BookModel> bookModels;
private Context context;
public BookListAdapter(Context context, int resource, ArrayList<BookModel> bookModels) {
super(context, resource, bookModels);
this.bookModels = bookModels;
this.context = context;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View rowView = convertView;
ViewHolder viewHolder;
if (rowView == null) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
rowView = inflater.inflate(R.layout.book_child_list, parent, false);
ViewHolder viewHolder = new ViewHolder();
viewHolder.bookIcon = (ImageView) rowView
.findViewById(R.id.bookIcon);
viewHolder.bookName = (TextView) rowView
.findViewById(R.id.bookName);
viewHolder.bookDetail = (TextView) rowView
.findViewById(R.id.bookDetail);
rowView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) rowView.getTag();
}
final BookModel bookModel = bookModels.get(position);
Picasso.with(context).load(bookModel.getBookImageUrl()).into(viewHolder.bookIcon);
viewHolder.bookName.setText(bookModel.getBookName());
viewHolder.bookDetail.setText(bookModel.getBookDetail());
return rowView;
}
#Override
public int getCount() {
return bookModels.size();
}
static class ViewHolder {
public ImageView bookIcon;
public TextView bookName;
public TextView bookDetail;
}
}
BookModel.java
public class BookModel {
private String bookName;
private String bookDetail;
private String bookImageUrl;
public BookModel() {
bookName = "";
bookDetail = "";
bookImageUrl = "";
}
public String getBookName() {
return bookName;
}
public void setBookName(String bookName) {
this.bookName = bookName;
}
public String getBookDetail() {
return bookDetail;
}
public void setBookDetail(String bookDetail) {
this.bookDetail = bookDetail;
}
public String getBookImageUrl() {
return bookImageUrl;
}
public void setBookImageUrl(String bookImageUrl) {
this.icons = bookImageUrl;
}
}
Where BookModel class is a class where you can wrap your data (book name, book detail, book image) and pass it as a list to the adapter.
for example :
protected Boolean doInBackground(final String... args) {
url = url + "?custom_iid=" + cus_id;
Log.d("Passing Url", url);
CustomListAdapter jParser = new CustomListAdapter();
JSONArray json = jParser.getJSONFromUrl(url);
ArrayList<BookModel> bookModelList = new ArrayList<BookModel>();
if (json != null) {
for (int i = 0; i < json.length(); i++) {
try {
BookModel bookModel = new BookModel();
JSONObject c = json.getJSONObject(i);
String b_image = c.getString("b_image");
String b_name = c.getString("b_name");
String b_detail = c.getString("b_publisher");
Log.d("detail", "" + b_image);
bookModel.setBookName(b_name);
bookModel.setBookDetail(b_detail);
bookModel.setBookImageUrl(b_image);
bookModelList.add(bookModel);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
if(bookModelList.size()>0) {
BookListAdapter bookListAdapter = new BookListAdapter(MainActivity.this, R.id.yourlistview, bookModelList );
}
return null;
}
I hope my answer can help you!
lv.setAdapter(adapter);
use AQuery lib.
and just write this code in your custom adapter:
AQuery aQuery = new AQuery(context);
aQuery.id(your image id).image(your url,true,true);
I am currently modifying an android app that I need to add a listview to an existing fragment. As I am new to android, I am just imitating the code from the apps. I created a new arrayadapter, a new class of data and made some modifies to the existing fragment class. The problem is I cannot see my list in the app. Below are my codes.
Adapter
public class RecordArrayAdapter extends ArrayAdapter<CheckInRecord.CheckInRec> {
private int resourceId;
private Context context;
private List<CheckInRecord.CheckInRec> checkInRec;
public RecordArrayAdapter(Context context, int resourceId, List<CheckInRecord.CheckInRec> checkInRec)
{
super(context, resourceId, checkInRec);
this.resourceId = resourceId;
this.context = context;
this.checkInRec = checkInRec;
}
public View getView(int position, View convertView, ViewGroup parent)
{
if (convertView == null){
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
convertView = inflater.inflate(resourceId, parent, false);
}
TextView textViewName = (TextView) convertView.findViewById(R.id.tv_name);
TextView textViewCheckInDate = (TextView) convertView.findViewById(R.id.tv_checkindate);
TextView textViewPoints = (TextView) convertView.findViewById(R.id.tv_points);
ImageView imageViewIcon = (ImageView) convertView.findViewById(R.id.iv_icon);
CheckInRecord.CheckInRec checkInrec = checkInRec.get(position);
textViewName.setText(checkInrec.providerName);
textViewCheckInDate.setText(checkInrec.checkInDate);
textViewPoints.setText(checkInrec.providerPoints);
ImageLoader.getInstance().displayImage(checkInrec.providerIcon, imageViewIcon, Utility.displayImageOptions);
return convertView;
}
public int getIsPrize(int position) {return (this.checkInRec.get(position).isPrize);}
}
Data type
public class CheckInRecord {
public int userPoints;
public String userName;
public String gender;
public String birthDate;
public String location;
public String userIcon;
public List<CheckInRec> checkInRecList = new ArrayList<CheckInRec>();
public void addCheckInRec(String providerName, String providerLocation, String providerIcon,
String checkInDate, int providerPoints, int isPrize){
CheckInRec checkInRec = new CheckInRec();
checkInRec.providerName = providerName;
checkInRec.providerLocation = providerLocation;
checkInRec.providerIcon = providerIcon;
checkInRec.checkInDate = checkInDate;
checkInRec.providerPoints = providerPoints;
checkInRec.isPrize = isPrize;
checkInRecList.add(checkInRec);
}
public List<String> recImages(){
List<String> resultList = new ArrayList<String>();
if (this.checkInRecList == null){
return resultList;
}
for (CheckInRec rec : this.checkInRecList){
resultList.add(rec.providerIcon);
}
return resultList;
}
public class CheckInRec{
public String providerName;
public String providerLocation;
public String providerIcon;
public String checkInDate;
public int providerPoints;
public int isPrize;
}
}
Fragment
public class MeFragment extends Fragment implements ApiRequestDelegate {
private TextView textViewName;
private TextView textViewPoints;
private ProgressDialog progressDialog;
private RecordArrayAdapter recordArrayAdapter;
private List<CheckInRecord.CheckInRec> checkInRec = new ArrayList<CheckInRecord.CheckInRec>();
public MeFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AppDataManager.getInstance().setAllowCheckIn(true);
progressDialog = ProgressDialog.show(getActivity(), "", "");
ApiManager.getInstance().checkInHistories(AppDataManager.getInstance().getUserToken(), AppDataManager.getInstance().getUserPhone(),
Utility.getPictureSize(), this);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_me, container, false);
textViewName = (TextView) view.findViewById(R.id.tv_name);
textViewPoints = (TextView) view.findViewById(R.id.tv_points);
ListView listViewCheckInRec = (ListView) view.findViewById(R.id.lv_histories);
recordArrayAdapter = new RecordArrayAdapter(this.getActivity().getApplicationContext(), R.layout.row_record, checkInRec);
listViewCheckInRec.setAdapter(recordArrayAdapter);
return view;
}
#Override
public void setMenuVisibility(boolean menuVisible) {
super.setMenuVisibility(menuVisible);
if (menuVisible) {
refreshName();
}
}
public void refreshName() {
progressDialog = ProgressDialog.show(getActivity(), "", "");
AppDataManager dataManager = AppDataManager.getInstance();
ApiManager.getInstance().checkInHistories(dataManager.getUserToken(), dataManager.getUserPhone(), Utility.getPictureSize(), this);
}
#Override
public void apiCompleted(ApiResult apiResult, HttpRequest httpRequest) {
if (progressDialog!=null){
progressDialog.dismiss();
}
if (!apiResult.success){
ApiManager.handleMessageForReason(apiResult.failReason, getActivity());
return;
}
CheckInRecord checkInRecord = (CheckInRecord) apiResult.valueObject;
if (checkInRecord != null){
textViewName.setText(checkInRecord.userName);
textViewPoints.setText(String.format("积分%d分", checkInRecord.userPoints));
// this.checkInRec.clear();
// this.checkInRec.addAll(checkInRecord.checkInRecList);
//
// recordArrayAdapter.notifyDataSetChanged();
}
}
}
The problem is I cannot see my list in the app.
That is because checkInRec does now have any elements inside of it.
I can really tell that it is empty because you commented this out:
// this.checkInRec.clear(); //clear the old data from the list
// this.checkInRec.addAll(checkInRecord.checkInRecList); //add all the data inside the checkInRecord.checkInRecList
//
// recordArrayAdapter.notifyDataSetChanged(); //refreshing the ListView to display the new data
now what are those doing is that clearing the old list array and adding the new set of data from checkInRecord.checkInRecList and refreshing the ListView so those new data are implemented/shown in your ListView.