I want to parse JSON from http://dev.onlinedominosid.com/newApi/Promotions?region=JKT
I created activity_main.xml like this:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" android:background="#F1F1F1"
tools:context=".MainActivity" >
<ListView
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
tools:listitem="#layout/row"/>
</LinearLayout>
and created listview (row.xml) like this:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="6dip" >
<LinearLayout
android:id="#+id/promotion_saja"
android:layout_width="150dp"
android:layout_height="160dp"
android:orientation="vertical">
<ImageView
android:id="#+id/image_promotion"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/ic_launcher"/>
</LinearLayout>
<RelativeLayout
android:id="#+id/detail_country"
android:layout_width="match_parent"
android:layout_height="160dp"
android:layout_toRightOf="#+id/promotion_saja"
android:layout_toEndOf="#+id/promotion_saja"
android:orientation="vertical"
android:layout_marginLeft="4dp">
<TextView
android:id="#+id/name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="TextView"
android:textSize="24sp"
android:textStyle="bold"
android:textAppearance="?android:attr/textAppearanceMedium"
android:layout_marginBottom="4dp"/>
<TextView
android:id="#+id/description"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/name"
android:layout_below="#+id/name"
android:text="TextView"
android:textAppearance="?android:attr/textAppearanceMedium"
android:layout_marginBottom="4dp"/>
<TextView
android:id="#+id/date_start"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/description"
android:layout_below="#+id/description"
android:text="TextView"
android:textSize="14sp"
android:textColor="#android:color/black"
android:textAppearance="?android:attr/textAppearanceMedium"
android:layout_marginBottom="4dp"/>
<TextView
android:id="#+id/date_end"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/date_start"
android:layout_below="#+id/date_start"
android:text="TextView"
android:textSize="14sp"
android:textColor="#android:color/black"
android:textAppearance="?android:attr/textAppearanceMedium"/>
</RelativeLayout>
</RelativeLayout>
after that I created promotion class like this:
public class Promotions {
private String name;
private String description;
private String date_start;
private String date_end;
private String image;
public Promotions() {
// TODO Auto-generated constructor stub
}
public Promotions(String name, String description, String date_start, String date_end, String image) {
super();
this.name = name;
this.description = description;
this.date_start = date_start;
this.date_end = date_end;
this.image = image;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getDate_start() {
return date_start;
}
public void setDate_start(String date_start) {
this.date_start = date_start;
}
public String getDate_end() {
return date_end;
}
public void setDate_end(String date_end) {
this.date_end = date_end;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
}
then I created promotion adapter like this:
import java.io.InputStream;
import java.util.ArrayList;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class PromotionAdapter extends ArrayAdapter<Promotions> {
ArrayList<Promotions> promoList;
LayoutInflater vi;
int Resource;
ViewHolder holder;
public PromotionAdapter(Context context, int resource, ArrayList<Promotions> objects) {
super(context, resource, objects);
vi = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
Resource = resource;
promoList = objects;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// convert view = design
View v = convertView;
if (v == null) {
holder = new ViewHolder();
v = vi.inflate(Resource, null);
holder.imageview = (ImageView) v.findViewById(R.id.image_promotion);
holder.Name = (TextView) v.findViewById(R.id.name);
holder.Description = (TextView) v.findViewById(R.id.description);
holder.Date_start = (TextView) v.findViewById(R.id.date_start);
holder.Date_end = (TextView) v.findViewById(R.id.date_end);
v.setTag(holder);
} else {
holder = (ViewHolder) v.getTag();
}
holder.imageview.setImageResource(R.drawable.ic_launcher);
new DownloadImageTask(holder.imageview).execute(promoList.get(position).getImage());
holder.Name.setText(promoList.get(position).getName());
holder.Description.setText(promoList.get(position).getDescription());
holder.Date_start.setText("Start: " + promoList.get(position).getDate_start());
holder.Date_end.setText("End: " + promoList.get(position).getDate_end());
return v;
}
static class ViewHolder {
public ImageView imageview;
public TextView Name;
public TextView Description;
public TextView Date_start;
public TextView Date_end;
}
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public DownloadImageTask(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}
}
I called the adapter in MainActivity like this:
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
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.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.ParseException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
public class MainActivity extends Activity {
ArrayList<Promotions> promoList;
PromotionAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
promoList = new ArrayList<Promotions>();
new JSONAsyncTask().execute("http://dev.onlinedominosid.com/newApi/Promotions?region=JKT");
ListView listview = (ListView)findViewById(R.id.list);
listview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long id) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), promoList.get(position).getName(), Toast.LENGTH_LONG).show();
}
});
}
class JSONAsyncTask extends AsyncTask<String, Void, Boolean> {
ProgressDialog dialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(MainActivity.this);
dialog.setMessage("Loading, please wait");
dialog.setTitle("Connecting server");
dialog.show();
dialog.setCancelable(false);
}
#Override
protected Boolean doInBackground(String... urls) {
try {
HttpGet httppost = new HttpGet(urls[0]);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httppost);
// StatusLine stat = response.getStatusLine();
int status = response.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONArray jsono = new JSONArray(data);
for(int i=0;i<jsono.length();i++){
//HashMap<String, String> promo = new HashMap<String, String>();
JSONObject object = jsono.getJSONObject(i);
Promotions actor = new Promotions();
actor.setName(object.getString("value_name_en"));
actor.setDescription(object.getString("value_desc_en"));
actor.setDate_start(object.getString("value_date_start"));
actor.setDate_end(object.getString("value_date_end"));
actor.setImage(object.getString("value_thumb_en"));
promoList.add(actor);
}
return true;
}
} catch (ParseException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
protected void onPostExecute(Boolean result) {
dialog.cancel();
if(result == false){
Toast.makeText(getApplicationContext(), "Unable to fetch data from server", Toast.LENGTH_LONG).show();
}else{
adapter = new PromotionAdapter(getApplicationContext(), R.layout.row, promoList);
ListView listview = (ListView)findViewById(R.id.list);
listview.setAdapter(adapter);
}
}
}
But get "Unable to fetch data from server", any wrong with my JSON parsing?
What should I do to correct that code (the correct code)?
Hi there is become slightly change in android for HttpGet etc...
You can use this code for get Json response of your Link.
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new JSONAsyncTask()
.execute("http://dev.onlinedominosid.com/newApi/Promotions?region=JKT");
}
public class JSONAsyncTask extends AsyncTask<String, Void, Boolean> {
ProgressDialog dialog;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
dialog = new ProgressDialog(MainActivity.this);
dialog.setMessage("Loading, please wait");
dialog.setTitle("Connecting server");
dialog.show();
dialog.setCancelable(false);
}
#Override
protected Boolean doInBackground(String... urls) {
String result = "";
// TODO Auto-generated method stub
try {
//New Code of Sun Microsystem for Parsing.
HttpURLConnection httpConnection;
URL url = new URL(urls[0]);
httpConnection = (HttpURLConnection) url.openConnection();
httpConnection.setRequestProperty("Accept", "application/json");
httpConnection.setReadTimeout(15000);
httpConnection.setConnectTimeout(15000);
httpConnection.setRequestMethod("GET");
httpConnection.setDoInput(true);
// StatusLine stat = response.getStatusLine();
int status = httpConnection.getResponseCode();
if (status == 200) {
InputStream iStream = httpConnection.getInputStream();
InputStreamReader isReader = new InputStreamReader(iStream);
BufferedReader br = new BufferedReader(isReader);
String line;
while ((line = br.readLine()) != null) {
result += line;
}
Log.e("Data", result);
//Create JSON Array of your Response.
JSONArray jsonArray = new JSONArray(result);
//Convert into Object.Here 0 no object is define,you can
//use for loop for all.
JSONObject json = jsonArray.getJSONObject(0);
//Get data using Key Value.
Log.e("ValueId", json.getString("value_id"));
return true;
}
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
#Override
protected void onPostExecute(Boolean result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
dialog.dismiss();
if (result == false)
Toast.makeText(getApplicationContext(),
"Unable to fetch data from server", Toast.LENGTH_LONG)
.show();
}
}
}
and dont forget to add permission of internet here
<uses-permission android:name="android.permission.INTERNET"/>
Related
I have a TextView and RatingBar in ListView, and i want to save value of RatingBar on each list in ListView, it is possible with custom adapter??
the code I use to do likes:
PertanyaanAdapter.java
package flix.yudi.pertanyaan3;
import android.app.Activity;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.RatingBar;
import android.widget.TextView;
import java.util.List;
class PertanyaanAdapter extends ArrayAdapter<Pertanyaan> {
private AppCompatActivity activity;
private List<Pertanyaan> movieList;
PertanyaanAdapter(AppCompatActivity context, int resource, List<Pertanyaan> objects) {
super(context, resource, objects);
this.activity = context;
this.movieList = objects;
}
#Override
public Pertanyaan getItem(int position) {
return movieList.get(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
LayoutInflater inflater = (LayoutInflater) activity.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = inflater.inflate(R.layout.item_listview, parent, false);
holder = new ViewHolder(convertView);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
//holder.ratingBar.getTag(position);
}
holder.ratingBar.setOnRatingBarChangeListener(onRatingChangedListener(position));
holder.ratingBar.setTag(position);
holder.ratingBar.setRating(getItem(position).getRatingStar());
holder.movieName.setText(getItem(position).getAsk());
return convertView;
}
private RatingBar.OnRatingBarChangeListener onRatingChangedListener(final int position) {
return new RatingBar.OnRatingBarChangeListener() {
#Override
public void onRatingChanged(RatingBar ratingBar, float v, boolean b) {
Pertanyaan item = getItem(position);
assert item != null;
item.setRatingStar(v);
Log.i("Adapter", "star: " + v);
}
};
}
private static class ViewHolder {
private RatingBar ratingBar;
private TextView movieName;
ViewHolder(View view) {
ratingBar = (RatingBar) view.findViewById(R.id.rate_img);
movieName = (TextView) view.findViewById(R.id.text);
}
}
}
Pertanyaan.java
package flix.yudi.pertanyaan3;
public class Pertanyaan {
private float ratingStar;
private String ask;
Pertanyaan(int ratingStar, String ask) {
this.ratingStar = ratingStar;
this.ask = ask;
}
float getRatingStar() {
return 0;
}
void setRatingStar(float ratingStar) {
this.ratingStar = ratingStar;
}
public String getAsk() {
return ask;
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
ListView listView;
ArrayList<Pertanyaan> listPertanyaan;
ArrayAdapter<Pertanyaan> adapter2;
ProgressDialog pDialog;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView)findViewById(R.id.list_view);
listPertanyaan = new ArrayList<>();
getpertanyaan get= new getpertanyaan();
get.execute();
adapter2 = new PertanyaanAdapter(this, R.layout.item_listview, listPertanyaan);
listView.setAdapter(adapter2);
}
protected void onStart() {
super.onStart();
}
private class getpertanyaan extends AsyncTask<Void, Void, Integer> {
ArrayList<Pertanyaan> list;
protected void onPreExecute() {
pDialog=new ProgressDialog(MainActivity.this);
pDialog.setTitle("Nama Dosen");
pDialog.setMessage("Menampilkan nama dosen... Mohon tunggu...!");
pDialog.setCancelable(false);
pDialog.show();
super.onPreExecute();
list = new ArrayList<>();
}
#Override
protected Integer doInBackground(Void... params) {
InputStream is = null;
String result = "";
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://flix.16mb.com/send_data.php");
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
// Get our response as a String.
is = entity.getContent();
} catch (IOException e) {
e.printStackTrace();
}
//convert response to string
try {
BufferedReader reader = null;
if (is != null) {
reader = new BufferedReader(new InputStreamReader(is, "utf-8"));
}
String line;
if (reader != null) {
while ((line = reader.readLine()) != null) {
result += line;
}
}
if (is != null) {
is.close();
}
//result=sb.toString();
} catch (Exception e) {
e.printStackTrace();
}
// parse json data
try {
JSONArray jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
JSONObject jsonObject = jArray.getJSONObject(i);
list.add(new Pertanyaan(0,jsonObject.getString("ask")));
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Integer result) {
if (pDialog.isShowing())
pDialog.dismiss();
listPertanyaan.addAll(list);
adapter2.notifyDataSetChanged();
}
}
}
but when I run the app, the RatingBar is untouchable, just each list of ListView is touch however I want to tap the RatingBar.
did I doing something wrong? help me please.
EDIT :
item_listview.xml
<RatingBar
android:id="#+id/rate_img"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/text"
android:numStars="5"
android:stepSize="1"
style="#style/Widget.AppCompat.RatingBar.Indicator" />
<TextView
android:id="#+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textStyle="bold" />
the RatingBar is read-only because of the style you are using.
style="#style/Widget.AppCompat.RatingBar.Indicator"
sets the attribute android:isIndicator to true which makes behave it, in the way are experiencing. You can either get rid of the line, or try to force android:isIndicator to false in your item_listview.xml
i was tring to load image using url.a single url is working properly. but i need to add a few more images to this page.i need to add this image s to a list view.pls tell me how can i add a string array to this code.
import java.io.IOException;
import org.apache.http.HttpResponse;
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.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
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.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
public class FareCrd extends Activity {
String image_url="http://movito.nervov.com/img/ace-hd.png";
String[] mString ={"http://movito.nervov.com/img/ace-hd.png",
"http://movito.nervov.com/img/Movito_Logo_M.png"};
JSONArray jsonary;
ListView list;
private Activity activity;
private String[] data;
private static View inflater=null;
//private String[] mStrings={"http://movito.nervov.com/img/ace-hd.png"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fare_crd);
list=(ListView)findViewById(R.id.farelist);
new ServConn().execute();
}
private void parsedata(String data){
//System.out.println(data);
try {
JSONObject json = new JSONObject(data);
jsonary = json.getJSONArray("data");
ListView list = (ListView) findViewById(R.id.farelist);
list.setAdapter(new DriverOrderList(getApplicationContext(),
R.layout.farecrd, new JSONObject[jsonary.length()]));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private class DriverOrderList extends ArrayAdapter<JSONObject> {
int listViewResource;
public DriverOrderList(Context context, int resource, JSONObject[] s) {
super(context, resource, s);
listViewResource = resource;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = ((LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(listViewResource, parent, false);
ImageLoader imgLoader = new ImageLoader(getApplicationContext());
JSONObject rowdata = new JSONObject();
int loader = R.drawable.stub;
try {
rowdata = jsonary.getJSONObject(position);
System.out.println(rowdata);
ImageLoader imgLoader1 = new ImageLoader(getApplicationContext());
ImageView img=(ImageView) row.findViewById(R.id.imgid);
imgLoader.DisplayImage(image_url, loader, img);
TextView nameTxt = (TextView) row.findViewById(R.id.truckname);
TextView idTxt = (TextView) row.findViewById(R.id.id);
TextView minrttv =(TextView) row.findViewById(R.id.minimumRate);
TextView kmrttxt =(TextView) row.findViewById(R.id.kilometerRate);
TextView mindurtv=(TextView) row.findViewById(R.id.minimumDuration);
TextView freewatintim = (TextView) row.findViewById(R.id.freeWaitingTime);
TextView minuterttxt =(TextView) row.findViewById(R.id.minuteRate);
TextView watingchrttv =(TextView)row.findViewById(R.id.waitingCharge);
double freewt=(Double) rowdata.get("freeWaitingTime");
double kmratetxt=(Double) rowdata.get("kilometerRate");
double mindurtxt=(Double) rowdata.get("minimumDuration");
double mindur= mindurtxt/60;
double minkmrttxt=(Double) rowdata.get("minimumKilometer");
double minrttxt=(Double) rowdata.get("minimumRate");
double mintrate=(Double) rowdata.get("minuteRate");
double minutrat=mintrate/60;
double watingchrtxt=(Double) rowdata.get("waitingCharge");
double waitchgunittxt=(Double) rowdata.get("waitingChargeUnit");
nameTxt.setText(rowdata.getString("truckModel"));
minrttv.setText("Rs."+minrttxt+" /-");
kmrttxt.setText("Rs."+kmratetxt+"/km after "+minkmrttxt+"km");
mindurtv.setText("first"+mindur+"hr and "+minkmrttxt+"km");
//minuterttxt.setText(minutrat+"/-");
freewatintim.setText("first "+freewt+"min free");
watingchrttv.setText("RS"+watingchrtxt+"after every "+waitchgunittxt+"min");
}
catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return row;
}
}
private class ServConn extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
System.out.println("do in backgrnd");
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet("http://movito.nervov.com/v1/trucks/miniTruckCategories");
httpget.setHeader(HTTP.CONTENT_TYPE, "application/json");
String replyString = "";
try {
HttpResponse response = httpclient.execute(httpget);
replyString = EntityUtils.toString(response
.getEntity());
} catch (ClientProtocolException e) {
System.out.println("ex: " + e);
} catch (IOException e) {
System.out.println("e: " + e);
}
return replyString;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
System.out.println(result);
result = "{\"data\":"+result+"}";
parsedata(result);
}
#Override
protected void onPreExecute() {}
#Override
protected void onProgressUpdate(Void... values) {}
}
}
Try to use Glide libreries instead od picasso .It might help full for you.Please look at following link which might help you out.
http://inthecheesefactory.com/blog/get-to-know-glide-recommended-by-google/en
try this code I am using Picasso library to populate ImageView,
if you are using android studio add this library using following code into your gradle file
compile 'com.squareup.picasso:picasso:2.5.2'
use following code,
It is complete example of how you can make a custom ListView, I didn't include code where you have to get he JSON data from WebService as i didn't want to make the code complicated, I will write a separate code where i will show how to read the data you are interested in.
XML
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ListView
android:id="#+id/CustomListViewActivity_listView"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
single_item.xml layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="50dp"
android:orientation="horizontal">
<TextView
android:id="#+id/single_item_textView"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_margin="4dp"
android:layout_weight="0.5"
android:text="New Text" />
<ImageView
android:id="#+id/single_item_imageView"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_margin="4dp"
android:layout_weight="0.5" />
</LinearLayout>
Code
public class CustomListViewActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_custom_list_view);
ArrayList<SingleItem> singleItems = new ArrayList<>();
singleItems.add(new SingleItem("http://movito.nervov.com/img/ace-hd.png","first Text"));
singleItems.add(new SingleItem("http://movito.nervov.com/img/Movito_Logo_M.png","Second Text"));
singleItems.add(new SingleItem("http://movito.nervov.com/img/ace-hd.png","third Text"));
singleItems.add(new SingleItem("http://movito.nervov.com/img/Movito_Logo_M.png","fourth Text"));
ListView listView = (ListView)findViewById(R.id.CustomListViewActivity_listView);
MyAdapter adapter = new MyAdapter(getApplicationContext(), R.layout.single_item,singleItems);
listView.setAdapter(adapter);
}
private class MyAdapter extends ArrayAdapter {
private ArrayList<SingleItem> singleItems;
private LayoutInflater layoutInflater;
private Context context;
private View single_View;
public MyAdapter(Context context, int resource, ArrayList<SingleItem> singleItems) {
super(context, resource, singleItems);
this.context = context;
this.singleItems = singleItems;
layoutInflater = LayoutInflater.from(this.context);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
ViewHolder holder = null;
if (row == null) {
row = layoutInflater.inflate(R.layout.single_item, parent, false);
holder = new ViewHolder();
holder.textView = (TextView) row.findViewById(R.id.single_item_textView);
holder.imageView = (ImageView) row.findViewById(R.id.single_item_imageView);
row.setTag(holder);
} else {
holder = (ViewHolder) row.getTag();
}
final SingleItem singleItem = singleItems.get(position);
holder.textView.setText("" + singleItem.getText());
Picasso.with(context).load(""+singleItem.getUrl()).into(holder.imageView);
return row;
}
private class ViewHolder {
// Instance Variable (state or data)
TextView textView;
ImageView imageView;
}
}
public class SingleItem {
private String url;
private String text;
public SingleItem() {
}
public SingleItem(String url, String text) {
this.url = url;
this.text = text;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
}
}
Output
As you will see the loading the images from the URL provided to the appropriate ImageView is taken care by Picasso, do make sure you add the permission for the internet in the AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET" />
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'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).
Here is my code :
public class Fragment1 extends SherlockFragment {
ListView lista;
ArrayList<String> items = new ArrayList<String>();
private ArrayList<MyListAdapter> thelista = new ArrayList<MyListAdapter>();
View rootView;
ListView list;
TextView title, price;
MyListAdapter adapter;
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// TODO Auto-generated method stub
super.onCreateOptionsMenu(menu, inflater);
MenuInflater blowup = this.getSherlockActivity()
.getSupportMenuInflater();
blowup.inflate(R.menu.menuxml, menu);
return;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.main, container, false);
ActionBar ab = this.getSherlockActivity().getSupportActionBar();
ab.setTitle("");
title = (TextView) rootView.findViewById(R.id.title);
price = (TextView) rootView.findViewById(R.id.details);
list = (ListView) rootView.findViewById(R.id.list);
SpinnerAdapter mSpinnerAdapter = ArrayAdapter.createFromResource(
this.getSherlockActivity(), R.array.phones_array,
android.R.layout.simple_spinner_dropdown_item);
ab.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
ab.setListNavigationCallbacks(mSpinnerAdapter, null);
StrictMode.enableDefaults();
getData();
return rootView;
}
public void getData() {
String result = "";
InputStream isr = null;
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httpost = new HttpPost(
"http://10.0.2.2/AndroidArabia/android3arabiya.php");
HttpResponse resposne = httpclient.execute(httpost);
HttpEntity entity = resposne.getEntity();
isr = entity.getContent();
} catch (Exception e) {
Log.e("log_tag", "error in http connection" + e.toString());
Toast.makeText(getSherlockActivity(),
"Couldn't Connect To The Internet", Toast.LENGTH_LONG)
.show();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
isr, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
isr.close();
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting Result " + e.toString());
}
try {
JSONArray jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
JSONObject json = jArray.getJSONObject(i);
thelista.add(new MyListAdapter(json.getString("PhoneName"),
json.getString("PhonePrice")));
}
list.setAdapter((ListAdapter) thelista);
} catch (Exception e) {
Log.e("lag_tag", "ERROR PARSING DATA" + e.toString());
Toast.makeText(getSherlockActivity(),
"Couldn't Connect To The Internet", Toast.LENGTH_LONG)
.show();
}
MyListAdapter Code :
public class MyListAdapter extends BaseAdapter {
private String[] data;
private String[] data2;
private Context context;
public MyListAdapter(String string, String string2) {
// TODO Auto-generated constructor stub
}
#Override
public int getCount() {
return data.length;
}
#Override
public Object getItem(int position) {
return data[position];
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View rowView = LayoutInflater.from(context).inflate(R.layout.pricelist,
parent, false);
TextView text1 = (TextView) rowView.findViewById(R.id.title);
TextView text2 = (TextView) rowView.findViewById(R.id.details);
text1.setText(data[position]);
text2.setText(data2[position]);
return rowView;
}
}
}
price list xml :
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="5dip" >
<LinearLayout
android:id="#+id/thumbnail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_marginRight="5dip"
android:background="#drawable/image_bg"
android:padding="3dip" >
<ImageView
android:id="#+id/list_image"
android:layout_width="50dip"
android:layout_height="50dip" />
</LinearLayout>
<TextView
android:id="#+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/thumbnail"
android:layout_toRightOf="#+id/thumbnail"
android:text="Smartphone Name"
android:textColor="#040404"
android:textSize="15dip"
android:textStyle="bold"
android:typeface="sans" />
<TextView
android:id="#+id/details"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#id/title"
android:layout_marginTop="1dip"
android:layout_toRightOf="#+id/thumbnail"
android:text="Smartphone Price"
android:textColor="#343434"
android:textSize="10dip" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:src="#drawable/rating" />
</RelativeLayout>
And Finally main xml :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<ListView
android:id="#+id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:divider="#b5b5b5"
android:dividerHeight="1dp" >
</ListView>
</LinearLayout>
I'm not an expert in custom layout but i'm getting an error in parsing the JSON Array into the custom listview. Of course my main goal is to fill the custom listview with the JSON array but i don't have any clue how to do it and non of question asked before have helped me.
Can anyone help me right here?
Here all the info, the program is stopping at the JSon catch exception and giving me the toastBox : Couldn't connect to the internet. any suggestion? :)
Fragment1.java
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;
import android.app.ActionBar;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SpinnerAdapter;
import android.widget.TextView;
import android.widget.Toast;
public class Fragment1 extends SherlockFragment {
ArrayList<String> items = new ArrayList<String>();
ArrayList<BeanClass> beanClass=new ArrayList<BeanClass>();
View rootView;
ListView list;
TextView title, price;
MyListAdapter adapter;
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// TODO Auto-generated method stub
super.onCreateOptionsMenu(menu, inflater);
MenuInflater blowup = this.getSherlockActivity()
.getSupportMenuInflater();
blowup.inflate(R.menu.menuxml, menu);
return;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.main, container, false);
ActionBar ab = this.getSherlockActivity().getSupportActionBar();
ab.setTitle("");
title = (TextView) rootView.findViewById(R.id.title);
price = (TextView) rootView.findViewById(R.id.details);
list = (ListView) rootView.findViewById(R.id.list);
SpinnerAdapter mSpinnerAdapter = ArrayAdapter.createFromResource(
this.getSherlockActivity(), R.array.phones_array,
android.R.layout.simple_spinner_dropdown_item);
ab.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
ab.setListNavigationCallbacks(mSpinnerAdapter, null);
StrictMode.enableDefaults();
getData();
return rootView;
}
public void getData() {
String result = "";
InputStream isr = null;
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httpost = new HttpPost(
"http://10.0.2.2/AndroidArabia/android3arabiya.php");
HttpResponse resposne = httpclient.execute(httpost);
HttpEntity entity = resposne.getEntity();
isr = entity.getContent();
} catch (Exception e) {
/* Log.e("log_tag", "error in http connection" + e.toString());
Toast.makeText(getSherlockActivity(),
"Couldn't Connect To The Internet", Toast.LENGTH_LONG)
.show();*/
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
isr, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
isr.close();
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting Result " + e.toString());
}
try {
JSONArray jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
JSONObject json = jArray.getJSONObject(i);
/* thelista.add(new MyListAdapter(json.getString("PhoneName"),
json.getString("PhonePrice")));*/
beanClass.add(new BeanClass(json.getString("PhoneName"),
json.getString("PhonePrice"));
}
list.setAdapter(new MyListAdapter(Fragment1.this, beanClass));
} catch (Exception e) {
Log.e("lag_tag", "ERROR PARSING DATA" + e.toString());
Toast.makeText(getSherlockActivity(),
"Couldn't Connect To The Internet", Toast.LENGTH_LONG)
.show();
}
Your Adapter
import java.util.ArrayList;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
public class MyListAdapter extends BaseAdapter {
private Context context;
private ArrayList<BeanClass> beanClass=new ArrayList<BeanClass>();
public MyListAdapter(Context context,ArrayList<BeanClass> beanClass) {
// TODO Auto-generated constructor stub
this.context=context;
this.beanClass=beanClass;
}
#Override
public int getCount() {
return beanClass.size();
}
#Override
public Object getItem(int position) {
return beanClass.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View rowView = LayoutInflater.from(context).inflate(R.layout.pricelist,
parent, false);
TextView text1 = (TextView) rowView.findViewById(R.id.title);
TextView text2 = (TextView) rowView.findViewById(R.id.details);
text1.setText(beanClass.get(position).phoneName);
text2.setText(beanClass.get(position).phonePrice);
return rowView;
}
}
}
BeanClasss
public class BeanClass {
String phoneName;
String phonePrice;
public String getPhoneName() {
return phoneName;
}
public String getPhonePrice() {
return phonePrice;
}
public void setPhoneName(String phoneName) {
this.phoneName = phoneName;
}
public void setPhonePrice(String phonePrice) {
this.phonePrice = phonePrice;
}
public BeanClass(String phoneName, String phonePrice) {
super();
this.phoneName = phoneName;
this.phonePrice = phonePrice;
}
}