I want to display image to GridView in Android Studio, but it always fail to fetch data. Can you tell me why?
MainActivity.Java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.amobi.picassodemo.Model.GridItem;
import com.amobi.picassodemo.adapter.GridViewAdapter;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class MainActivity extends ActionBarActivity {
private static final String TAG = MainActivity.class.getSimpleName();
private GridView mGridView;
private ProgressBar mProgressBar;
private GridViewAdapter mGridAdapter;
private ArrayList<GridItem> mGridData;
private String URL="http://lomapod.azurewebsites.net/readBarang.php?id_penjual=1";
private String FEED_URL = "http://lomapod.esy.es/assets/bronco_turkey.jpg";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mGridView = (GridView) findViewById(R.id.gridView);
mProgressBar = (ProgressBar) findViewById(R.id.progressBar);
//Initialize with empty data
mGridData = new ArrayList<>();
mGridAdapter = new GridViewAdapter(this, R.layout.grid_item_layout, mGridData);
mGridView.setAdapter(mGridAdapter);
//Start download
new AsyncHttpTask().execute(URL);
mProgressBar.setVisibility(View.VISIBLE);
}
public class AsyncHttpTask extends AsyncTask<String, Void, Integer> {
#Override
protected Integer doInBackground(String... params) {
Integer result = 0;
try {
// Create Apache HttpClient
HttpClient httpclient = new DefaultHttpClient();
HttpResponse httpResponse = httpclient.execute(new HttpGet(params[0]));
int statusCode = httpResponse.getStatusLine().getStatusCode();
// 200 represents HTTP OK
if (statusCode == 200) {
String response = streamToString(httpResponse.getEntity().getContent());
parseResult(response);
result = 1; // Successful
} else {
result = 0; //"Failed
}
} catch (Exception e) {
Log.d(TAG, e.getLocalizedMessage());
}
return result;
}
#Override
protected void onPostExecute(Integer result) {
// Download complete. Let us update UI
if (result == 1) {
mGridAdapter.setGridData(mGridData);
} else {
Toast.makeText(MainActivity.this, "Failed to fetch data!", Toast.LENGTH_SHORT).show();
}
mProgressBar.setVisibility(View.GONE);
}
}
String streamToString(InputStream stream) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(stream));
String line;
String result = "";
while ((line = bufferedReader.readLine()) != null) {
result += line;
}
// Close stream
if (null != stream) {
stream.close();
}
return result;
}
private void parseResult(String result) {
try {
JSONObject response = new JSONObject(result);
JSONArray posts = response.optJSONArray("posts");
GridItem item;
for (int i = 0; i < posts.length(); i++) {
JSONObject post = posts.optJSONObject(i);
String title = post.optString("title");
item = new GridItem();
item.setBarang(title);
JSONArray attachments = post.getJSONArray("attachments");
if (null != attachments && attachments.length() > 0) {
JSONObject attachment = attachments.getJSONObject(0);
if (attachment != null)
item.setImage(attachment.getString(FEED_URL));
}
mGridData.add(item);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
GridItem.Java
public class GridItem {
private String image;
private String barang;
public GridItem() {
super();
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getBarang() {
return barang;
}
public void setBarang(String barang) {
this.barang = barang;
}
}
GridViewAdapter.Java
package com.amobi.picassodemo.adapter;
import android.app.Activity;
import android.content.Context;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.amobi.picassodemo.Model.GridItem;
import com.amobi.picassodemo.R;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
/**
* Created by Nicky-PC on 4/9/2016.
*/
public class GridViewAdapter extends ArrayAdapter<GridItem> {
private Context mContext;
private int layoutResourceId;
private ArrayList<GridItem> mGridData = new ArrayList<GridItem>();
public GridViewAdapter(Context mContext, int layoutResourceId, ArrayList<GridItem> mGridData) {
super(mContext, layoutResourceId, mGridData);
this.layoutResourceId = layoutResourceId;
this.mContext = mContext;
this.mGridData = mGridData;
}
/**
* Updates grid data and refresh grid items.
* #param mGridData
*/
public void setGridData(ArrayList<GridItem> mGridData) {
this.mGridData = mGridData;
notifyDataSetChanged();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
ViewHolder holder;
if (row == null) {
LayoutInflater inflater = ((Activity) mContext).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new ViewHolder();
holder.titleTextView = (TextView) row.findViewById(R.id.grid_item_title);
holder.imageView = (ImageView) row.findViewById(R.id.grid_item_image);
row.setTag(holder);
} else {
holder = (ViewHolder) row.getTag();
}
GridItem item = mGridData.get(position);
holder.titleTextView.setText(Html.fromHtml(item.getBarang()));
Picasso.with(mContext).load(item.getImage()).into(holder.imageView);
return row;
}
static class ViewHolder {
TextView titleTextView;
ImageView imageView;
}
}
Related
I have been working on an android project where I need to fetch data from server and display in a listview. The first retrieval is done successfully but from second retrieval onwards the fetched data's are placed below the previously fetched data. How can I refresh the listview to view the fetched data in the listview? The codes I used are given below.
package com.example.sohan.patient;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Sohan on 5/20/2016.
*/
public class Doctors_layout extends Fragment implements AdapterView.OnItemSelectedListener{
View myView;
Spinner spinner;
String selectedCity;
Context myContext;
String jsonResult;
JSONObject jsonObject;
JSONArray jsonArray;
ContactAdapter contactAdapter;
String JSON_String;
ListView listView;
Button button;
int check=0;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
myView = inflater.inflate(R.layout.doctors_directory, container, false);
myContext = inflater.getContext();
contactAdapter = new ContactAdapter(myContext, R.layout.row_layout);
spinner = (Spinner)myView.findViewById(R.id.spinner);
listView = (ListView)myView.findViewById(R.id.listView);
listView.setAdapter(contactAdapter);
spinner.setOnItemSelectedListener(this);
List<String> city = new ArrayList<String>();
city.add("Choose a City");
city.add("Chittagong");
city.add("Dhaka");
ArrayAdapter<String> aAdapter = new ArrayAdapter<String>(myContext, android.R.layout.simple_spinner_item ,city);
aAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(aAdapter);
return myView;
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
//contactAdapter.notifyDataSetChanged();
if(check==0) {
((TextView) parent.getChildAt(0)).setTextSize(21);
if (position == 0) {
nothing();
} else {
check++;
selectedCity = parent.getItemAtPosition(position).toString();
Toast.makeText(myContext, "Check value: "+check, Toast.LENGTH_LONG).show();
retrieveInfo ri = new retrieveInfo();
ri.execute(selectedCity); // notifydata
}
}
else{
contactAdapter.notifyDataSetChanged();
selectedCity = parent.getItemAtPosition(position).toString();
retrieveInfo ri = new retrieveInfo();
ri.execute(selectedCity);
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
public void nothing(){
//Toast.makeText(myContext, "Default position 0", Toast.LENGTH_LONG).show();
}
class retrieveInfo extends AsyncTask<String, Void, String> { // send data to server
String myUrl;
protected void onPreExecute() {
myUrl ="http://bdpricelist.com/patient/retrieveMedicalName.php"; // change php script
}
protected String doInBackground(String... args) {
String city;
String result = null;
city = args[0];
JSONArray jsonArray = null;
try{
URL url = new URL(myUrl);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String data_to_send = URLEncoder.encode("city", "UTF-8")+"="+URLEncoder.encode(city,"UTF-8");
bufferedWriter.write(data_to_send);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream is = httpURLConnection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
while ((JSON_String = reader.readLine()) != null)
{
sb.append(JSON_String+"\n");
}
reader.close();
httpURLConnection.disconnect();
is.close();
return sb.toString().trim();
}catch(MalformedURLException e){
e.printStackTrace();
}catch(IOException f){
f.printStackTrace();
}
return null;
}
protected void onPostExecute(String result) {
jsonResult = result;
parseJSON(jsonResult);
//jsonResult="";
}
}
public void delete(String city) {
Fragment Dl = new Doctors_layout();
FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.content_frame, Dl);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
public void parseJSON(String json){
Contacts contacts=null;
try {
jsonObject = new JSONObject(json);
jsonArray = jsonObject.getJSONArray("patient");
int count = 0;
String name;
while (count < jsonArray.length()) {
JSONObject jo = jsonArray.getJSONObject(count);
name = jo.getString("Medical"); // data's are send to store in and print in listview
contacts = new Contacts(name);
contactAdapter.add(contacts);
count++;
}
//contactAdapter.add(contacts.getMedicalName());
} catch (Exception e) {
e.printStackTrace();
}
}
}
And my adapter class is given below
package com.example.sohan.patient;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Sohan on 6/9/2016.
*/
public class ContactAdapter extends ArrayAdapter {
//ContactHolder contactHolder;
List list = new ArrayList();
ContactAdapter contactAdapter;
List receivedList = new ArrayList();
View row;
ContactHolder contactHolder;
int count =0;
public ContactAdapter(Context context, int resource) {
super(context, resource);
}
public void add(Contacts object) {
// list.clear();
super.add(object);
list.add(object);
//notifyDataSetChanged();
Toast.makeText(getContext().getApplicationContext(), "Entry without delete ", Toast.LENGTH_SHORT).show();
}
#Override
public int getCount() {
return list.size();
}
#Override
public void clear() {
super.clear();
}
#Override
public boolean isEmpty() {
return super.isEmpty();
}
#Override
public void notifyDataSetChanged() {
super.notifyDataSetChanged();
}
public void deleteEntry(){
list.clear();
Toast.makeText(getContext().getApplicationContext(), "List cleared before entry ", Toast.LENGTH_SHORT).show();
}
#Override
public Object getItem(int position) {
return list.get(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
//count++;
row = convertView;
if(row==null){
LayoutInflater layoutInflater = (LayoutInflater)this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = layoutInflater.inflate(R.layout.row_layout,parent,false);
contactHolder = new ContactHolder();
contactHolder.MedicalName =(TextView) row.findViewById(R.id.textView5);
row.setTag(contactHolder);
}
else{
contactHolder = (ContactHolder)row.getTag();
}
contactHolder = new ContactHolder();
contactHolder.MedicalName =(TextView) row.findViewById(R.id.textView5);
Contacts contacts = (Contacts)this.getItem(position);
contactHolder.MedicalName.setText(contacts.getMedicalName());
return row;
}
static class ContactHolder{
TextView MedicalName;
}
}
Instead of having add(Contacts object) in your adapter, have a method where you clear the current items in the list and update with the newly retrieved items.
private void updateContactList(List<Contacts> updatedList) {
list.clear();
list.addAll(updatedList);
notifyDataSetChanged();
}
and inside parseJSON(String json)
List<Contacts> newList = new ArrayList<>();
while (count < jsonArray.length()) {
JSONObject jo = jsonArray.getJSONObject(count);
name = jo.getString("Medical");
contacts = new Contacts(name);
newList.add(contacts);
count++;
}
contactAdapter.updateContactList(newList);
The new data is being shown after the old data because you are adding new data to the existing one in parseJSON().
If you want to replace the old data with new one then remove these lines from onCreateView and add inside parseJSON(), right after while loop.
contactAdapter = new ContactAdapter(myContext, R.layout.row_layout);
listView.setAdapter(contactAdapter);
I receive a JSON array from the server that looks like this,
[{"id":"3","name":"Spanish 101","uid":"54f22e5c87cbd3.52439435","did":"fba6a04d1d6375fbdbb102953e984002"},
{"id":"4","name":"Calc","uid":"54f22e5c87cbd3.52439435","did":"fb7f4ba1eae22eb396dc7cbd465a10b4"},
{"id":"5","name":"Stats 250","uid":"54f22e5c87cbd3.52439435","did":"f6adca44250056c17fec56530faee7c9"}]
I want to take this information and put it into a listview
This is my code that is suppose to process this JSON aray and put it into a listview
package com.example.library;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.AsyncTask;
public class FetchDataTask extends AsyncTask<String, Void, String>{
private final FetchDataListener listener;
private String msg;
public FetchDataTask(FetchDataListener listener) {
this.listener = listener;
}
#Override
protected String doInBackground(String... params) {
if(params == null) return null;
// get url from params
String url = params[0];
try {
// create http connection
HttpClient client = new DefaultHttpClient();
HttpGet httpget = new HttpGet(url);
// connect
HttpResponse response = client.execute(httpget);
// get response
HttpEntity entity = response.getEntity();
if(entity == null) {
msg = "No response from server";
return null;
}
// get response content and convert it to json string
InputStream is = entity.getContent();
return streamToString(is);
}
catch(IOException e){
msg = "No Network Connection";
}
return null;
}
#Override
protected void onPostExecute(String sJson) {
if(sJson == null) {
if(listener != null) listener.onFetchFailure(msg);
return;
}
try {
// convert json string to json array
JSONArray aJson = new JSONArray(sJson);
// create apps list
List<Application> apps = new ArrayList<Application>();
for(int i=0; i<aJson.length(); i++) {
JSONObject json = aJson.getJSONObject(i);
Application app = new Application();
app.setTitle(json.getString("name"));
// add the app to apps list
apps.add(app);
}
//notify the activity that fetch data has been complete
if(listener != null) listener.onFetchComplete(apps);
} catch (JSONException e) {
msg = "Invalid response";
if(listener != null) listener.onFetchFailure(msg);
return;
}
}
/**
* This function will convert response stream into json string
* #param is respons string
* #return json string
* #throws IOException
*/
public String streamToString(final InputStream is) throws IOException{
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
}
catch (IOException e) {
throw e;
}
finally {
try {
is.close();
}
catch (IOException e) {
throw e;
}
}
return sb.toString();
}
}
FetchDataListener
package com.example.library;
import java.util.List;
public interface FetchDataListener {
public void onFetchComplete(List<Application> data);
public void onFetchFailure(String msg);
}
I am currently only trying to place the name into the listview, when I run this code what happens is only the first array gets put into the listview. So there is only one list item and it has the name Spanish 101.
Why aren't the other array names being put into the listview?
Application Adapter
package com.example.library;
import java.text.NumberFormat;
import java.util.List;
import android.content.Context;
import android.content.res.Resources;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.example.R;
public class ApplicationAdapter extends ArrayAdapter<Application>{
private List<Application> items;
public ApplicationAdapter(Context context, List<Application> items) {
super(context, R.layout.app_custom_list, items);
this.items = items;
}
#Override
public int getCount() {
return items.size();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if(v == null) {
LayoutInflater li = LayoutInflater.from(getContext());
v = li.inflate(R.layout.app_custom_list, null);
}
Application app = items.get(position);
if(app != null) {
TextView titleText = (TextView)v.findViewById(R.id.titleTxt);
if(titleText != null) titleText.setText(app.getTitle());
}
return v;
}
}
Get and Set
package com.example.library;
public class Application {
private String title;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
MainActivity that has ListView
package com.example;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.ClipData;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.example.R;
import com.example.library.Application;
import com.example.library.ApplicationAdapter;
import com.example.library.DatabaseHandler;
import com.example.library.FetchDataListener;
import com.example.library.FetchDataTask;
import com.example.library.UserFunctions;
import java.util.HashMap;
import java.util.List;
public class MainActivity extends ListActivity implements FetchDataListener {
private ProgressDialog dialog;
ProgressDialog nDialog;
AlertDialog.Builder dlgAlert;
ListView listView ;
TextView tv;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
tv = (TextView) findViewById(R.id.tv);
nDialog = new ProgressDialog(MainActivity.this);
//Action bar information
android.app.ActionBar mActionBar = getActionBar();
assert mActionBar != null;
mActionBar.setDisplayShowHomeEnabled(false);
mActionBar.setDisplayShowTitleEnabled(false);
LayoutInflater mInflater = LayoutInflater.from(this);
View mCustomView = mInflater.inflate(R.layout.custom_actionbar, null);
//FIX THISSSSS TO LOGOUT BUTTON
RelativeLayout settingButton = (RelativeLayout) mCustomView
.findViewById(R.id.settingButton);
settingButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
UserFunctions logout = new UserFunctions();
logout.logoutUser(getApplicationContext());
Intent startup = new Intent(getApplicationContext(), StartUp.class);
startup.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(startup);
finish();
}
});
mActionBar.setCustomView(mCustomView);
mActionBar.setDisplayShowCustomEnabled(true);
//End action bar information
}//End onCreate
private void initView() {
// show progress dialog
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
HashMap user = new HashMap();
user = db.getUserDetails();
String uid = user.get("unique_id").toString();
dialog = ProgressDialog.show(this, "", "Loading...");
String url = "www.example.com";
FetchDataTask task = new FetchDataTask(this);
task.execute(url);
}
#Override
public void onFetchComplete(List<Application> data) {
// dismiss the progress dialog
if(dialog != null) dialog.dismiss();
// create new adapter
ApplicationAdapter adapter = new ApplicationAdapter(this, data);
// set the adapter to list
setListAdapter(adapter);
}
#Override
public void onFetchFailure(String msg) {
// dismiss the progress dialog
if(dialog != null) dialog.dismiss();
// show failure message
Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
}
}//End Activity
This is how i deal with ListView and CustomAdapter
in onCreate() of Activity
//Photos Model List
photoList = new ArrayList<Photos>();
//ListView
lvGalleryPhotos = (ListView) parentView.findViewById(R.id.lvGalleryPhotos);
//My CustomAdapter
pgAdapter = new PhotoGalleryAdapter(photoList, getSherlockActivity());
//Setting adapter to GridView
lvGalleryPhotos.setAdapter(pgAdapter);
//Parsing JSON
for(int i=0;i<10;i++){
//each result contains details about a image
JSONObject result = results.getJSONObject(i);
//Real Parsing
int width = result.getInt("width");
int height = result.getInt("height");
String title = result.getString("titleNoFormatting");
String url = result.getString("unescapedUrl");
//Make it workable so replace \u003d with =
String tbUrl = result.getString("tbUrl").replace("\u003d", "=");
//Creating photo object and inserting all collected information into it.
Photos photo = new Photos();
photo.setHeight(height);
photo.setWidth(width);
photo.setTitle(title);
photo.setURL(url);
photo.setTbUrl(tbUrl);
//Adding each Photo Object to PhotoList
photoList.add(photo);
}
//Informing that data has changed
pgAdapter.notifyDataSetChanged();
My Custom Adapter
public class PhotoGalleryAdapter extends BaseAdapter {
ImageLoader mImageLoader;
List<Photos> photoList;
Context mContext;
BlowIt blw;
LayoutInflater mLInflater;
public PhotoGalleryAdapter(List<Photos> photoList,Context mContext){
this.photoList = photoList;
this.mContext = mContext;
blw = new BlowIt(mContext);
}
#Override
public int getCount() {
return photoList.size();
}
#Override
public Object getItem(int position) {
return photoList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
//Creating layout inflater
if(mLInflater==null){
mLInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
//Inflating Layout
if(convertView==null){
convertView = mLInflater.inflate(R.layout.gallery_single_photo,parent,false);
}
//Getting Object
final Photos photo = photoList.get(position);
//Single Image
NetworkImageView nivGalleryPhoto = (NetworkImageView) convertView.findViewById(R.id.nivGalleryPhoto);
TextView tvPhotoName = (TextView) convertView.findViewById(R.id.tvPhotoName);
TextView tvPhotoDesc = (TextView) convertView.findViewById(R.id.tvPhotoDesc);
final String photoDescr = photo.getHeight()+"x"+photo.getWidth();
nivGalleryPhoto.setImageUrl(photo.getTbUrl(), mImageLoader);
tvPhotoName.setText(photo.getTitle());
tvPhotoDesc.setText(photoDescr);
convertView.setTag(photo);
convertView.setId(position);
//This will trigger when ever the user clicks on a specific image
convertView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//This will prompt automatically context menu
v.showContextMenu();
}
});
return convertView;
}
}
and the layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/llPhotosFragmentRoot"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ListView
android:id="#+id/lvGalleryPhotos"
android:layout_height="wrap_content"
android:layout_width="match_parent"
></ListView>
</LinearLayout>
and the gallery_single_photo.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:padding="10dp"
android:layout_height="wrap_content" >
<!-- <com.android.volley.toolbox.NetworkImageView -->
<com.android.volley.toolbox.NetworkImageView
android:id="#+id/nivGalleryPhoto"
android:layout_height="90dp"
android:scaleType="centerCrop"
android:layout_width="75dp"
android:contentDescription="#string/dummy_desc"
/>
<TextView
android:id="#+id/tvPhotoName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="16sp"
android:textStyle="bold"
android:layout_alignTop="#+id/nivGalleryPhoto"
android:layout_marginLeft="5dp"
android:layout_toRightOf="#+id/nivGalleryPhoto"
android:text="Large Text"/>
<TextView
android:id="#+id/tvPhotoDesc"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/tvPhotoName"
android:layout_below="#+id/tvPhotoName"
android:text="Medium Text"
android:textSize="13sp"
android:textColor="#color/border_black" />
</RelativeLayout>
and all the above codes can make a listView with items like this
Use ViewHolder design pattern in your getView(...):
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
ViewHolder holder;
if(v == null) {
LayoutInflater li = LayoutInflater.from(getContext());
v = li.inflate(R.layout.app_custom_list, null);
holder = new ViewHolder();
holder.titleText = (TextView)v.findViewById(R.id.titleTxt);
v.setTag(holder);
}
else
holder = (ViewHolder) v.getTag()
Application app = items.get(position);
if(app != null) {
if(titleText != null)
holder.titleText.setText(app.getTitle());
}
return v;
}
static class ViewHolder {
TextView titleText;
}
I have the following issue :
I'm having a GridView which displays alot of ImageViews , If I start scrolling the Items randomly start to change so there are wrong images at wrong positions and they start swapping everytime from position to position.
ImageAdapter
package com.zippyscore.pr0gramm.Adapter;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import com.zippyscore.pr0gramm.MainActivity;
import com.zippyscore.pr0gramm.Util.Constants;
import java.io.InputStream;
/**
* Created by Dominik on 16.01.2015.
*/
public class ImageAdapter extends BaseAdapter {
private Context mContext;
public ImageAdapter(Context c) {
mContext = c;
}
public int getCount() {
return MainActivity.mainPagePostLoader.getPostList().size();
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
// create a new ImageView for each item referenced by the Adapter
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder vh;
if (convertView == null) {
convertView = new ImageView(mContext);
vh = new ViewHolder();
vh.imageView = (ImageView) convertView;
convertView.setTag(vh);
} else {
vh = (ViewHolder) convertView.getTag();
}
new DownloadImageTask(vh.imageView).execute(MainActivity.mainPagePostLoader.getPosts().get(MainActivity.mainPagePostLoader.getPostList().get(position)).getThumb());
return convertView;
}
protected class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public DownloadImageTask(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = "http://" + Constants.THUMB_DOMAIN + urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Pr0gramm", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}
private class ViewHolder{
public ViewHolder(){}
public ImageView imageView;
//public TextView textView;
//Add any views you want to use in getView here
}
}
MainPagePostLoader(should be irrelevant)
package com.zippyscore.pr0gramm.Network;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Point;
import android.os.AsyncTask;
import android.util.Log;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import com.zippyscore.pr0gramm.CustomViews.ThumbImageView;
import com.zippyscore.pr0gramm.MainActivity;
import com.zippyscore.pr0gramm.Post.MainPagePost;
import com.zippyscore.pr0gramm.Util.GridRow;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/**
* Created by Dominik on 13.01.2015.
*/
public class MainPagePostLoader{
int chunksLoaded;
int lastPromoted;
private HashMap<String, MainPagePost> posts = new HashMap<String, MainPagePost>();
private List<String> postList = new ArrayList<String>();
private NetworkHelper networkHelper;
public MainPagePostLoader(){
chunksLoaded = 0;
lastPromoted = 0;
networkHelper = new NetworkHelper();
}
public HashMap<String, MainPagePost> getPosts(){
return this.posts;
}
public List<String> getPostList(){
return this.postList;
}
public void loadNextChunk(){
if(chunksLoaded==0){
String serverResponse = networkHelper.connect("http://pr0gramm.com/api/items/get?flags=1&promoted=1"); //TODO ADD FLAG SUPPORT
if(serverResponse!=null){
try {
JSONObject serverResponseJSON = new JSONObject(serverResponse);
if(serverResponseJSON.has("items")) {
JSONArray postsJSON = serverResponseJSON.getJSONArray("items");
for(int i = 0; i < postsJSON.length();i++){
JSONObject post = postsJSON.getJSONObject(i);
posts.put(String.valueOf(post.getInt("id")),new MainPagePost(post.getInt("id"),post.getInt("promoted"),post.getInt("up"), post.getInt("down"), post.getLong("created"), post.getString("image"),post.getInt("flags"),post.getInt("mark"), post.getString("source"),post.getString("thumb"),post.getString("user")));
postList.add(String.valueOf(post.getInt("id")));
MainActivity.activity.runOnUiThread(new Runnable() {
#Override
public void run() {
MainActivity.imageAdapter.notifyDataSetChanged();
}
});
//addThumb(i);
}
}
chunksLoaded++;
} catch (JSONException e) {
Log.e("Pr0gramm","JSON Parse error : " + e.getMessage() + "|" + e.getCause());
}
}else{
Log.e("Pr0gramm", "Chunk loading error");
}
}else{
try {
String serverResponse = networkHelper.connect("http://pr0gramm.com/api/items/get?older=" + String.valueOf(posts.get(postList.size() - 1).getID()));
JSONObject serverResponseJSON = new JSONObject(serverResponse);
if(serverResponseJSON.has("items")){
JSONArray postsJSON = serverResponseJSON.getJSONArray("items");
for(int i = 0; i < postsJSON.length();i++){
JSONObject post = postsJSON.getJSONObject(i);
posts.put(String.valueOf(post.getInt("id")),new MainPagePost(post.getInt("id"),post.getInt("promoted"),post.getInt("up"), post.getInt("down"), post.getLong("created"), post.getString("image"),post.getInt("flags"),post.getInt("mark"), post.getString("source"),post.getString("thumb"),post.getString("user")));
postList.add(String.valueOf(post.getInt("id")));
MainActivity.imageAdapter.notifyDataSetChanged();
//addThumb(i + (postList.size()-1));
}
}
chunksLoaded++;
}catch(JSONException e){
Log.e("Pr0gramm", "JSON Parse error : " + e.getMessage() + "|" + e.getCause());
}
}
}
/*
private void addThumb(int id){
int currentRow = MainActivity.gridRows.size() - 1;
Point size = new Point();
MainActivity.defaultDisplay.getSize(size);
if(currentRow!=-1) {
if (MainActivity.gridRows.get(currentRow).getItemCount() < MainActivity.maxItemsPerRow) {
final ThumbImageView thumbImageView = new ThumbImageView(MainActivity.context, id);
thumbImageView.setLayoutParams(new RelativeLayout.LayoutParams(size.x / MainActivity.maxItemsPerRow, size.x / MainActivity.maxItemsPerRow));
thumbImageView.setX(MainActivity.gridRows.get(currentRow).getItemCount() * size.x / MainActivity.maxItemsPerRow);
thumbImageView.setY(currentRow * size.x / MainActivity.maxItemsPerRow);
MainActivity.activity.runOnUiThread(new Runnable() {
#Override
public void run() {
MainActivity.rootLayout.addView(thumbImageView);
}
});
MainActivity.gridRows.get(currentRow).addItem();
} else {
MainActivity.gridRows.add(new GridRow());
addThumb(id);
}
}else{
MainActivity.gridRows.add(new GridRow());
addThumb(id);
}
} */
}
Consider using the Square Picasso library for this rather than rolling your own:
http://square.github.io/picasso/
I'm new to Android so struggling to learn best practices etc and working mainly with tutorials.
I have my app doing what I want it to do using a custom listview. My problem is understanding exactly how it works as there is not an actual listview in the code.
What I want to do is add a container above the listview, but everything I have tried just doesn't seem to work and with it being a custom adapter, I'm struggling to find many resources.
Here is my fragment:
package info.androidhive.slidingmenu;
import android.annotation.TargetApi;
import android.app.ListFragment;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewStub;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class PhotosFragment extends ListFragment {
private static final String TAG = MainActivity.class.getSimpleName();
private List<ListViewItem> mItems; // ListView items list
JSONObject obj;
JSONArray stories;
class RequestTask extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... uri) {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
String responseString = null;
try {
response = httpclient.execute(new HttpGet(uri[0]));
StatusLine statusLine = response.getStatusLine();
if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
responseString = out.toString();
//Do anything with response..
Log.d(TAG, responseString);
} else {
//Closes the connection.
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
} catch (ClientProtocolException e) {
//TODO Handle problems..
Log.d(TAG, String.valueOf(e));
} catch (IOException e) {
//TODO Handle problems..
Log.d(TAG, String.valueOf(e));
}
return responseString;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Log.e(TAG, result);
try {
obj = new JSONObject(result);
stories = obj.getJSONArray("stories");
// initialize the items list
mItems = new ArrayList<ListViewItem>();
for (int i = 0; i < stories.length(); i++) {
JSONObject storyObj = stories.getJSONObject(i);
if (!storyObj.has("Advert")) {
newsStories newsStories = new newsStories();
newsStories.setTitle(storyObj.getString("subject"));
newsStories.setBody(storyObj.getString("body"));
mItems.add(new ListViewItem(newsStories.getTitle(), newsStories.getBody(), ""));
} else {
newsStories newsStories = new newsStories();
newsStories.setThumbnailUrl(storyObj.getString("Advert"));
mItems.add(new ListViewItem("", "", newsStories.getThumbnailUrl()));
}
// initialize and set the list adapter
setListAdapter(new ListViewDemoAdapter(getActivity(), mItems));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
public class newsStories {
private String name, thumbnailUrl, body;
public String getTitle() {
return name;
}
public void setTitle(String name) {
this.name = name;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body.substring(0, 150);
}
public String getThumbnailUrl() {
return thumbnailUrl;
}
public void setThumbnailUrl(String thumbnailUrl) {
//Check if thumbnail exists, if so take out spaces and replace with -
this.thumbnailUrl = thumbnailUrl;
}
}
}
#TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
// View importPanel = ((ViewStub) getActivity().findViewById(R.id.stub_import)).inflate();
new RequestTask().execute("http://www.myjsonurl.co.uk");
// remove the dividers from the ListView of the ListFragment
getListView().setDivider(null);
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
// retrieve theListView item
ListViewItem item = mItems.get(position);
// do something
Toast.makeText(getActivity(), item.title, Toast.LENGTH_SHORT).show();
}
public class ListViewItem {
public final String title; // the text for the ListView item title
public final String description; // the text for the ListView item description
public final String adUrl;
//public final Drawable image;
public ListViewItem(String title, String description, String Advert_Url) {
Log.e("Advert:", Advert_Url);
if (Advert_Url != null && !Advert_Url.isEmpty()) {
String Advert = "http://alinktomyadvert.co.uk";
Log.e("TITLE: ", title);
this.title = "";
this.description = "";
this.adUrl = Advert;
} else {
this.title = title;
this.description = description;
this.adUrl = "";
}
}
}
}
If somebody can point me in the right direction I'd be so grateful.
EDIT:
Following #Sufian's advise I now have the following:
package info.androidhive.slidingmenu;
import android.annotation.TargetApi;
import android.app.Fragment;
import android.app.ListFragment;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewStub;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class PhotosFragment extends Fragment {
public PhotosFragment(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_photos, container, false);
return rootView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
new RequestTask().execute("http://www.myaddress.co.uk/app/index.php?Type=8&catid=7&userid=4");
Log.v("created", "onActivityCreated()");
setHasOptionsMenu(true);
//mProgressBar = (ProgressBar) getView().findViewById(R.id.progressBar);
ListView mListView = (ListView) getView().findViewById(R.id.listView2);
//mTvEmpty = (TextView) getView().findViewById(R.id.textView);
ArrayAdapter<ListViewItem> adapter = new ArrayAdapter<ListViewItem>(getActivity(), android.R.layout.simple_list_item_1, mItems);
// load your data to your mListView
mListView.setAdapter(adapter); //NULL POINTER
}
private static final String TAG = MainActivity.class.getSimpleName();
private List<ListViewItem> mItems; // ListView items list
JSONObject obj;
JSONArray stories;
//
class RequestTask extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... uri) {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
String responseString = null;
try {
response = httpclient.execute(new HttpGet(uri[0]));
StatusLine statusLine = response.getStatusLine();
if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
responseString = out.toString();
//Do anything with response..
Log.d(TAG, responseString);
} else {
//Closes the connection.
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
} catch (ClientProtocolException e) {
//TODO Handle problems..
Log.d(TAG, String.valueOf(e));
} catch (IOException e) {
//TODO Handle problems..
Log.d(TAG, String.valueOf(e));
}
return responseString;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Log.e(TAG, result);
try {
obj = new JSONObject(result);
stories = obj.getJSONArray("stories");
// initialize the items list
mItems = new ArrayList<ListViewItem>();
for (int i = 0; i < stories.length(); i++) {
JSONObject storyObj = stories.getJSONObject(i);
if (!storyObj.has("Advert")) {
newsStories newsStories = new newsStories();
newsStories.setTitle(storyObj.getString("subject"));
newsStories.setBody(storyObj.getString("body"));
mItems.add(new ListViewItem(newsStories.getTitle(), newsStories.getBody(), ""));
} else {
newsStories newsStories = new newsStories();
newsStories.setThumbnailUrl(storyObj.getString("Advert"));
mItems.add(new ListViewItem("", "", newsStories.getThumbnailUrl()));
}
// initialize and set the list adapter
//setListAdapter(new ListViewDemoAdapter(getActivity(), mItems));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
public class newsStories {
private String name, thumbnailUrl, body;
public String getTitle() {
return name;
}
public void setTitle(String name) {
this.name = name;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body.substring(0, 150);
}
public String getThumbnailUrl() {
return thumbnailUrl;
}
public void setThumbnailUrl(String thumbnailUrl) {
//Check if thumbnail exists, if so take out spaces and replace with -
this.thumbnailUrl = thumbnailUrl;
}
}
}
//
// #TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
// #Override
// public void onViewCreated(View view, Bundle savedInstanceState) {
// super.onViewCreated(view, savedInstanceState);
//
//
// // View importPanel = ((ViewStub) getActivity().findViewById(R.id.stub_import)).inflate();
// new RequestTask().execute("http://www.myjsonurl.co.uk");
// // remove the dividers from the ListView of the ListFragment
// getListView().setDivider(null);
// }
//
// #Override
// public void onListItemClick(ListView l, View v, int position, long id) {
// // retrieve theListView item
// ListViewItem item = mItems.get(position);
//
// // do something
// Toast.makeText(getActivity(), item.title, Toast.LENGTH_SHORT).show();
// }
//
public class ListViewItem {
public final String title; // the text for the ListView item title
public final String description; // the text for the ListView item description
public final String adUrl;
//public final Drawable image;
public ListViewItem(String title, String description, String Advert_Url) {
Log.e("Advert:", Advert_Url);
if (Advert_Url != null && !Advert_Url.isEmpty()) {
String Advert = "http://www.myaddress.co.uk/images/websitelogo.png?width=700&height=200";
Log.e("TITLE: ", title);
this.title = "";
this.description = "";
this.adUrl = Advert;
} else {
this.title = title;
this.description = description;
this.adUrl = "";
}
}
}
}
I'm now getting a null pointer exception on the set adapter command - I'm a little unsure where to debug from here. I'm assuming it means the list is null?
EDIT 2
Logcat:
01-19 05:27:30.371 1287-1287/info.androidhive.slidingmenu D/OpenGLRenderer﹕ Enabling debug mode 0
01-19 05:27:31.031 1287-1287/info.androidhive.slidingmenu I/Choreographer﹕ Skipped 60 frames! The application may be doing too much work on its main thread.
01-19 05:27:57.901 1287-1287/info.androidhive.slidingmenu V/created﹕ onActivityCreated()
01-19 05:28:08.271 1287-1287/info.androidhive.slidingmenu D/dalvikvm﹕ GC_FOR_ALLOC freed 326K, 9% free 4066K/4468K, paused 24ms, total 26ms
01-19 05:28:08.471 1287-1287/info.androidhive.slidingmenu D/AndroidRuntime﹕ Shutting down VM
01-19 05:28:08.471 1287-1287/info.androidhive.slidingmenu W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0xb3ac2ba8)
01-19 05:28:08.511 1287-1287/info.androidhive.slidingmenu E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: info.androidhive.slidingmenu, PID: 1287
java.lang.NullPointerException
at info.androidhive.slidingmenu.PhotosFragment$RequestTask.onPostExecute(PhotosFragment.java:130)
at info.androidhive.slidingmenu.PhotosFragment$RequestTask.onPostExecute(PhotosFragment.java:52)
at android.os.AsyncTask.finish(AsyncTask.java:632)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5017)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
fragment_photos.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">
<ProgressBar
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/progressBar"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="190dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Text"
android:id="#+id/textView"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="63dp" />
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/listView2"
android:layout_below="#+id/progressBar"
android:layout_centerHorizontal="true" />
</RelativeLayout>
EDIT 3
package info.androidhive.slidingmenu;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.text.Html;
import android.text.Layout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
import java.util.List;
public class ListViewDemoAdapter extends ArrayAdapter<PhotosFragment.ListViewItem> {
public ListViewDemoAdapter(Context context, List<PhotosFragment.ListViewItem> items) {
super(context, R.layout.listview_item, items);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder;
if(convertView == null) {
// inflate the GridView item layout
LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(R.layout.listview_item, parent, false);
// initialize the view holder
viewHolder = new ViewHolder();
viewHolder.ivIcon = (ImageView) convertView.findViewById(R.id.ivIcon);
viewHolder.tvTitle = (TextView) convertView.findViewById(R.id.tvTitle);
viewHolder.tvDescription = (TextView) convertView.findViewById(R.id.tvDescription);
convertView.setTag(viewHolder);
} else {
// recycle the already inflated view
viewHolder = (ViewHolder) convertView.getTag();
}
// update the item view
PhotosFragment.ListViewItem item = getItem(position);
//viewHolder.ivIcon.setImageDrawable(item.image);
viewHolder.tvTitle.setText((Html.fromHtml(item.title)));
viewHolder.tvDescription.setText(Html.fromHtml(item.description));
if (!item.adUrl.isEmpty()) {
Picasso.with(getContext())
.load(item.adUrl)
.into(viewHolder.ivIcon);
viewHolder.ivIcon.setVisibility(viewHolder.ivIcon.VISIBLE);
viewHolder.ivIcon.setOnClickListener(new View.OnClickListener() {
//#Override
public void onClick(View v) {
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.myaddress.co.uk"));
getContext().startActivity(browserIntent);
}
});
}else {
viewHolder.ivIcon.setVisibility(viewHolder.ivIcon.GONE);
}
return convertView;
}
/**
* The view holder design pattern prevents using findViewById()
* repeatedly in the getView() method of the adapter.
*
* #see
*/
private static class ViewHolder {
ImageView ivIcon;
TextView tvTitle;
TextView tvDescription;
}
}
ListFragment comes with a ListView, a ProgressBar (displayed till you write setListShown(true);) and a TextView (which is shown when the ListView has no items.
If you want to add anything above ListView, the easy way to do that is to replace ListFragment with Fragment and inflating your own XML. Like below:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_home, container, false);
}
And setting up your fields and populating data in onActivityCreated(), like:
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Log.v("created", "onActivityCreated()");
setHasOptionsMenu(true);
mProgressBar = (ProgressBar) getView().findViewById(R.id.progressBar1);
mListView = (ListView) getView().findViewById(R.id.listView1);
mTvEmpty = (TextView) getView().findViewById(R.id.tv_empty);
// load your data to your mListView
}
Edit:
Update your onPostExecute() to:
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Log.e(TAG, result);
try {
obj = new JSONObject(result);
stories = obj.getJSONArray("stories");
// initialize the items list
mItems = new ArrayList<ListViewItem>();
for (int i = 0; i < stories.length(); i++) {
JSONObject storyObj = stories.getJSONObject(i);
if (!storyObj.has("Advert")) {
newsStories newsStories = new newsStories();
newsStories.setTitle(storyObj.getString("subject"));
newsStories.setBody(storyObj.getString("body"));
mItems.add(new ListViewItem(newsStories.getTitle(), newsStories.getBody(), ""));
}
else {
newsStories newsStories = new newsStories();
newsStories.setThumbnailUrl(storyObj.getString("Advert"));
mItems.add(new ListViewItem("", "", newsStories.getThumbnailUrl()));
}
// initialize and set the list adapter
//setListAdapter(new ListViewDemoAdapter(getActivity(), mItems));
}
//mProgressBar = (ProgressBar) getView().findViewById(R.id.progressBar);
ListView mListView = (ListView) getView().findViewById(R.id.listView2);
//mTvEmpty = (TextView) getView().findViewById(R.id.textView);
Log.d("mListView: ", String.valueOf(mListView));
ArrayAdapter<ListViewItem> adapter = new ArrayAdapter<ListViewItem>(getActivity(), android.R.layout.simple_list_item_1, mItems);
Log.d("Adapter: ", String.valueOf(adapter));
// load your data to your mListView
mListView.setAdapter(adapter);
}
catch (JSONException e) {
e.printStackTrace();
}
}
You were creating adapter even if mItems was null (putting it after catch would run it always).
My project works without error, but upon loading, images are not loaded in the Listview.
Here is a sample image
sample at the first working image
But after dragging ListView, all images loads.
sample draggened image load
Please Help. Sorry bad english.
Categoryadapter.java
package com.medyasef.dernek.tjod;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.http.AndroidHttpClient;
import android.os.AsyncTask;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/**
* Created by olkunmustafa on 26.09.2013.
*/
public class CategoryAdapter extends BaseAdapter {
private String LOG_NAME = "HATA";
private List<Categoryicerikler> list_view;
private HashMap<Integer,Bitmap> bitmaplist;
private Context mContext;
private Categories categories = new Categories();
public CategoryAdapter(List<Categoryicerikler> list_view, Context mContext) {
this.list_view = list_view;
this.mContext = mContext;
bitmaplist = new HashMap<Integer, Bitmap>();
for (int i = 0; i < list_view.size() ; i++) {
Categoryicerikler bitmap_icerikler = list_view.get(i);
setBitmapFromURL(bitmap_icerikler.getCategory_post_image(),i);
}
}
/*
Burada resimleri çekmek için thread oluşturuyoruz.
Resim linkini ve ImageView'i veriyoruz ve ekrana basmasını sağlıyoruz.
*/
public void setBitmapFromURL(final String src,final int value) {
new Thread(
new Runnable()
{
#Override
public void run() {
HttpURLConnection connection= null;
try {
URL url = new URL(src);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setDoInput(true);
connection.setDoOutput(true);
connection.connect();
InputStream input = connection.getInputStream();
final Bitmap myBitmap = BitmapFactory.decodeStream(input);
try {
bitmaplist.put(value,myBitmap);
}
catch (Exception e){
Log.d(LOG_NAME,e.getMessage());
Log.d(LOG_NAME,"Resim ekleme işlemi başarısız.");
}
} catch (IOException e) {
e.printStackTrace();
}
finally {
connection.disconnect();
}
}
}).start();
}
#Override
public int getCount() {
return list_view.size();
}
#Override
public Object getItem(int position) {
return list_view.get(position);
}
#Override
public long getItemId(int position) {
return list_view.indexOf(getItem(position));
}
#Override
public View getView(int position, View convertview, ViewGroup viewGroup) {
Categoryicerikler categoryicerikler = list_view.get(position);
ViewHolder holder = null;
if(convertview==null){
Log.d(LOG_NAME,"sonuc");
convertview = LayoutInflater.from(mContext).inflate(R.layout.categories,viewGroup,false);
holder = new ViewHolder();
holder.txtTitle = (TextView) convertview.findViewById(R.id.category_posttitle);
holder.txtDate = (TextView) convertview.findViewById(R.id.category_postdate);
holder.imageView = (ImageView) convertview.findViewById(R.id.category_image);
convertview.setTag(holder);
Categories.categoryAdapter.notifyDataSetChanged();
}
else {
holder = (ViewHolder) convertview.getTag();
}
holder.txtTitle.setText(categoryicerikler.getCategory_posttitle());
holder.txtDate.setText(categoryicerikler.getCategory_postdate());
try {
holder.imageView.setImageBitmap(bitmaplist.get(position));
}
catch (Exception e){
}
return convertview;
}
/*private view holder class*/
private class ViewHolder {
ImageView imageView;
TextView txtTitle;
TextView txtDate;
}
}
Categoryicerikler.java
package com.medyasef.dernek.tjod;
import android.graphics.Bitmap;
import android.widget.ImageView;
/**
* Created by olkunmustafa on 26.09.2013.
*/
public class Categoryicerikler {
private String category_posttitle;
private String category_postdate;
private String category_post_content;
private String category_post_image;
public Categoryicerikler( String category_posttitle, String category_postdate, String category_post_content,String post_image) {
this.category_posttitle = category_posttitle;
this.category_postdate = category_postdate;
this.category_post_content = category_post_content;
this.category_post_image = post_image;
}
public String getCategory_posttitle() {
return category_posttitle;
}
public void setCategory_posttitle(String category_posttitle) {
this.category_posttitle = category_posttitle;
}
public String getCategory_postdate() {
return category_postdate;
}
public void setCategory_postdate(String category_postdate) {
this.category_postdate = category_postdate;
}
public String getCategory_post_content() {
return category_post_content;
}
public void setCategory_post_content(String category_post_content) {
this.category_post_content = category_post_content;
}
public String getCategory_post_image() {
return category_post_image;
}
public void setCategory_post_image(String category_post_image) {
this.category_post_image = category_post_image;
}
}
Categories.java
package com.medyasef.dernek.tjod;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.SystemClock;
import android.text.Html;
import android.util.Log;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONException;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
/**
* Created by olkunmustafa on 25.09.2013.
*/
public class Categories extends Activity {
private List<Categoryicerikler> content_list;
public static CategoryAdapter categoryAdapter;
private ListView main_category;
private static HashMap<Integer,Bitmap> bitmaplist;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_categories);
main_category = (ListView) findViewById(R.id.main_category);
new GetCategory().execute();
}
private class GetCategory extends AsyncTask<Void,Void,String> {
#Override
protected void onPreExecute() {
Toast.makeText(Categories.this, "İslem Baslıyor Bekleyiniz", Toast.LENGTH_SHORT).show();
}
#Override
protected String doInBackground(Void... voids) {
/*
Burada internete bağlanıp json veriyi string cinsinden çekiyoruz.
*/
InternetConnection internetcon = new InternetConnection();
String json_result = internetcon.get_json_data();
return json_result;
}
#Override
protected void onPostExecute(String data) {
/*
Gelen string veriyi json_to_list_view metoduna veriyorum
Bu metot gelen json verisinin içeriklerini doldurarak bana birt liste dönderir.
*/
try {
content_list = GetJson.json_to_list_view(data);
} catch (JSONException e) {
Log.d("Json_Error","Json çekilirken hata oluştu");
}
categoryAdapter = new CategoryAdapter(content_list,Categories.this);
main_category.setAdapter(categoryAdapter);
}
}
}
If you simply want to load images in a list view, I would recommend you to use Picasso
Its simple, fast and does nearly everything automatically for you. You also don't have to care about canceling request on activity destroy. So I guess this would be the best start for you, if you simply want to load images into a ImageView in a ListView.
for instance in your adapter you could use:
Picasso.with(context)
.load(url)
.placeholder(R.drawable.placeholder)
.error(R.drawable.error)
.into(imageView);
Where imageview is the ImageView of your listview cell
Use universal image loader library and then following way
---------------------------------------------------------
1 - options = new DisplayImageOptions.Builder()
.showStubImage(R.drawable.physicalgift_normal)
.cacheInMemory()
.cacheOnDisc()
.displayer(new RoundedBitmapDisplayer(10))
.build();
imageLoader=ImageLoader.getInstance();
ImageLoaderConfiguration imgconfig=ImageLoaderConfiguration.createDefault(context);
imageLoader.init(imgconfig);
----------------------------------------------------------
2 - String url=list.get(position).getThumbUrl();
if(url != null && url !="")
imageLoader.displayImage(Utils.getEncodedUrl(url), holder.img, options);
------------------------------------------------------------
3 - SubCatAdapter adapter = new SubCatAdapter(SubCategoryActivity.this,
mlist);
list.setAdapter(adapter);
------------------------------------------------------------
full example is here
public class SubCatAdapter extends BaseAdapter {
private ArrayList<SubcategoryData> list;
private LayoutInflater inflator;
public ImageLoader imageLoader;
private DisplayImageOptions options;
public SubCatAdapter(Context context, ArrayList<SubcategoryData> mlist) {
super();
this.list = mlist;
this.inflator = LayoutInflater.from(context);
options = new DisplayImageOptions.Builder()
.showStubImage(R.drawable.physicalgift_normal)
.cacheInMemory()
.cacheOnDisc()
.displayer(new RoundedBitmapDisplayer(10))
.build();
imageLoader=ImageLoader.getInstance();
ImageLoaderConfiguration imgconfig=ImageLoaderConfiguration.createDefault(context);
imageLoader.init(imgconfig);
}
public int getCount() {
// TODO Auto-generated method stub
return list.size();
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return list.get(position);
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View view = convertView;
ViewHolder holder = null;
if (convertView == null) {
view = inflator.inflate(R.layout.row_subcat, null);
holder = new ViewHolder();
holder.txt_Name = (TextView) view.findViewById(R.id.txt_name);
holder.img=(ImageView)view.findViewById(R.id.img_row);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
holder.txt_Name.setText(list.get(position).getName());
String url=list.get(position).getThumbUrl();
if(url != null && url !="")
imageLoader.displayImage(Utils.getEncodedUrl(url), holder.img, options);
return view;
}
static class ViewHolder {
TextView txt_Name;
ImageView img;
}
}