I'm making an app and I have an activity called SearchActivity. I have two custom ListViews and one works well. My problem is the list used with AdapterEventos. When I start the app nothing appears in this list.
The data from this list is added from a Post (DescarregarEventos method) and I think the problem is because the ArrayAdapter eventos is empty. If you see my code [1], the log that I print before the setAdapter of this list returns empty.
Does somebody know how I can fix this?
[1] http://pastebin.com/FZacCrHD
Thanks
EDIT:
I'm already see that POST returns the all data requested.
RELEVANT CODE:
public class SearchActivity extends ListActivity {
public ArrayList<Evento> eventos = new ArrayList<Evento>();
static final String TAG = "AsyncTaskParseJson.java";
static final HttpClient httpclient = new DefaultHttpClient();
public class Evento {
public String nome;
public String local;
public String inicio;
public Evento(String nome, String local, String inicio) {
this.nome = nome;
this.local = local;
this.inicio = inicio;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getLocal() {
return local;
}
public void setLocal(String local) {
this.local = local;
}
public String getInicio() {
return inicio;
}
public void setInicio(String inicio) {
this.inicio = inicio;
}
}
public class AdapterEventos extends ArrayAdapter<Evento> {
private final Context context;
private final ArrayList<Evento> eventosArrayList;
public AdapterEventos(Context context, ArrayList<Evento> eventos) {
super(context, R.layout.listeventos, eventos);
this.context = context;
this.eventosArrayList = eventos;
}
public View getViewEventos(int position, View convertView, ViewGroup parent) {
//Create inflater
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//Get rowView from inflater
View LinhaEventoView = inflater.inflate(R.layout.listeventos, parent, false);
//Get the text view from the rowView
TextView nomeView = (TextView) LinhaEventoView.findViewById(R.id.tvNomeEvento);
TextView localView = (TextView) LinhaEventoView.findViewById(R.id.tvLocalEvento);
TextView inicioView = (TextView) LinhaEventoView.findViewById(R.id.tvInicioEvento);
//Set the text for textView
nomeView.setText(eventosArrayList.get(position).getNome());
localView.setText(eventosArrayList.get(position).getLocal());
inicioView.setText(eventosArrayList.get(position).getInicio());
//return rowView
return LinhaEventoView;
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
setContentView(R.layout.search_activity);
new DescarregarEventos().execute();
ListView ListEventos=(ListView)findViewById(R.id.listEventos);
Log.d("eventos","eventos: " + eventos);
ListEventos.setAdapter(new AdapterEventos(this, eventos));
public class DescarregarEventos extends AsyncTask<String, String, String> {
JSONArray dataJsonArr = null;
protected String doInBackground(String... arg) {
HttpPost httppost = new HttpPost(eventosUrl);
String evt = null;
try {
//Criar parĂ¢metros para o Post.
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("eventos", "data"));
httppost.setEntity(new UrlEncodedFormEntity(params));
//Executar o Post.
ResponseHandler<String> responseHandler = new BasicResponseHandler();
evt = httpclient.execute(httppost, responseHandler);
} catch (UnsupportedEncodingException e) {
Log.d("HTTP","ERRO A ADICIONAR OS PARĂ‚METROS PARA O POST EM \"DescarregarEventos()\"");
e.printStackTrace();
} catch (IOException e) {
Log.d("HTTP", "ERRO EM \"DescarregarEventos()\"");
e.printStackTrace();
}
return evt;
}
// Tratar a resposta do Post e adicionar ao array respetivo.
public void onPostExecute(String evt) {
try {
JSONArray E = new JSONArray(evt);
for (int i = 0; i < E.length(); i++) {
JSONObject evento = E.getJSONObject(i);
eventos.add(new Evento(evento.getString("nome"),evento.getString("localizacao"),evento.getString("data_inicio")));
}
} catch (JSONException e) {
Log.d("HTTP","ERRO A TRATAR OS EVENTOS EM \"DescarregarEventos() \" - \"onPostExecute()\"");
e.printStackTrace();
}
}
}
}
You can try to notify after data is added to adapter. So, at the end of onCreate function you can add the following line:
mAdapter.notifyDataSetChanged();
Related
So I have a Recyclerview which holding items with images, I want to load images into the items but when I do that I got a lot of fps drops.
I read that I need to use another thread for the network part and I tried to do that as you can see, and it seems good to me but I can't figure out how to stop the fps drops and make the scrolling in the Recyclerview smooth, this Recyclerview supposed to hold between 10 and 100. Am I supposed to run the activity in a thread?
Note: The fps drops occur with 10 items.
calling to the HttpWrapper.LoadImageFromWebOperations function in OnBindViewHolder.
HomeAdapter.java
public class HomeAdapter extends RecyclerView.Adapter<HomeAdapter.HomeViewHolder>{
private Context context;
private ArrayList<RecipeModel> items;
public HomeAdapter(Context context, ArrayList<RecipeModel> items) {
this.context = context;
this.items = items;
}
#Override
public HomeAdapter.HomeViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(context);
View v = inflater.inflate(R.layout.home_item,null);
HomeAdapter.HomeViewHolder holder = new HomeAdapter.HomeViewHolder(v);
return holder;
}
public void addItem(RecipeModel item){
this.items.add(item);
notifyDataSetChanged();
}
#Override
public void onBindViewHolder(HomeAdapter.HomeViewHolder holder, final int position) {
RecipeModel model = items.get(position);
holder.name.setText(model.getName());
holder.directions.setText(model.getDirections()[0]);
Drawable drawable = HttpWrapper.LoadImageFromWebOperations(model.getImageSource());
holder.image.setImageDrawable(drawable);
}
#Override
public int getItemCount() {
return items.size();
}
class HomeViewHolder extends RecyclerView.ViewHolder{
TextView name;
TextView directions;
ImageView image;
public HomeViewHolder(View itemView) {
super(itemView);
name = (TextView) itemView.findViewById(R.id.recipe_name);
directions = (TextView) itemView.findViewById(R.id.recipe_directions);
image = (ImageView) itemView.findViewById(R.id.recipe_image);
}
}
HttpWrapper.java
public class HttpWrapper {
String responseMsg = "";
private OkHttpClient client;
private Request request;
public static final String base_url = "http://kingtimmy.pythonanywhere.com";
public static final String home_route = "/home/";
public HttpWrapper() {
client = new OkHttpClient();
}
public ArrayList<RecipeModel> get_home_recipes(int recipe_num){
ArrayList<RecipeModel> models = new ArrayList<RecipeModel>();
request = new Request.Builder().url(base_url + home_route + String.valueOf(recipe_num)).build();
responseMsg = "";
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
responseMsg = "Error: " + e.getMessage();
}
#Override
public void onResponse(Call call, Response response) throws IOException {
responseMsg = response.body().string();
}
});
while(responseMsg.equals("")){
continue;
}
String[] jsons = responseMsg.split("]-]");
for (int i = 0; i < jsons.length; i++){
models.add(makeRecipeModel(jsons[i]));
}
return models;
}
public RecipeModel makeRecipeModel(String msg){
JSONObject nodeRoot = null;
RecipeModel model;
try {
nodeRoot = new JSONObject(msg);
String[] directions = nodeRoot.get("directions").toString().split("\\n");
String[] ingredients = nodeRoot.get("ingredients").toString().split("\\n");
String image_source = nodeRoot.get("image").toString();
String source_url = nodeRoot.get("source_url").toString();
String name = nodeRoot.get("name").toString();
int id = Integer.valueOf(nodeRoot.get("id").toString());
model = new RecipeModel(directions,ingredients,image_source,source_url,name,id);
} catch (JSONException e) {
model = null;
}
return model;
}
public static Drawable LoadImageFromWebOperations(final String url) {
ExecutorService executor = Executors.newSingleThreadExecutor();
Callable<Drawable> callable = new Callable<Drawable>() {
#Override
public Drawable call() {
try {
InputStream is = (InputStream) new URL(url).getContent();
Drawable d = Drawable.createFromStream(is, "src name");
return d;
} catch (Exception e) {
System.out.println("Exc=" + e);
return null;
}
}
};
Future<Drawable> future = executor.submit(callable);
// future.get() returns 2 or raises an exception if the thread dies, so safer
try {
Drawable d = future.get();
executor.shutdown();
return d;
} catch (Exception e) {
return null;
}
}
What am I doing wrong?
Instead of writing your own thread and code to fetch, parse, decode and load the image, give Glide a try. It does all that for you with a simple single line code and loads the image in your ImageView
i am trying to send Data (ID value) from one activity to other
but it wouldn't send correct data , i want it to send only ID Value of Clicked Item to next activity , here is my code
public class Order extends AppCompatActivity {
private ListView lvUsers;
private ProgressDialog dialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sub);
dialog = new ProgressDialog(this);
dialog.setIndeterminate(true);
dialog.setCancelable(false);
dialog.setMessage("Loading, please wait.....");
lvUsers = (ListView) findViewById(R.id.lvUsers);
new JSONTask().execute("http://146.185.178.83/resttest/order");
}
public class JSONTask extends AsyncTask<String, String, List<OrderModel> > {
#Override
protected void onPreExecute(){
super.onPreExecute();
dialog.show();
}
#Override
protected List<OrderModel> doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line ="";
while ((line=reader.readLine()) !=null){
buffer.append(line);
}
String finalJson = buffer.toString();
JSONArray parentArray = new JSONArray(finalJson);
List<OrderModel> orderModelList = new ArrayList<>();
Gson gson = new Gson();
for (int i = 0; i < parentArray.length(); i++) {
JSONObject finalObject = parentArray.getJSONObject(i);
OrderModel orderModel = gson.fromJson(finalObject.toString(), OrderModel.class);
orderModelList.add(orderModel);
}
return orderModelList;
}catch (MalformedURLException e) {
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if(connection !=null) {
connection.disconnect();
}
try {
if (reader !=null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(List<OrderModel> result) {
super.onPostExecute(result);
dialog.dismiss();
OrderAdapter adapter = new OrderAdapter(getApplicationContext(), R.layout.row_order, result);
lvUsers.setAdapter(adapter);
}
}
public class OrderAdapter extends ArrayAdapter {
public List<OrderModel> orderModelList;
private int resource;
private LayoutInflater inflater;
public OrderAdapter(Context context, int resource, List<OrderModel> objects) {
super(context, resource, objects);
orderModelList = objects;
this.resource = resource;
inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if(convertView == null){
holder = new ViewHolder();
convertView=inflater.inflate(resource, null);
holder.bOrderNo = (Button) convertView.findViewById(R.id.bOrderNo);
convertView.setTag(holder);
}else {
holder = (ViewHolder) convertView.getTag();
}
final int orderId = orderModelList.get(position).getId();
holder.bOrderNo.setText("Order No: " + orderModelList.get(position).getOrderId());
holder.bOrderNo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(Order.this, OrderSelected.class);
intent.putExtra("parameter_name", orderId);
startActivity(intent);
}
});
return convertView;
}
class ViewHolder{
private Button bOrderNo;
}
}
}
The holder gets executed in loop i guess is why it wouldn't send right Id.
How do i get it to send only Id of the clicked orderId
you can check this link to see how json Response looks like http://146.185.178.83/resttest/order
You have a silly mistake in your code . I have edited single line in your code . I think you are getting same "orderId" every time instead of actual "orderId". Check this one . I hope your problem will resolve .
final int index = position;
holder.bOrderNo.setText("Order No: " + orderModelList.get(position).getOrderId());
holder.bOrderNo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(Order.this, OrderSelected.class);
intent.putExtra("parameter_name", orderModelList.get(index).getId());
startActivity(intent);
}
});
Please try
In place of
intent.putExtra("parameter_name", orderId);
Please put
intent.putExtra("parameter_name", orderModelList.get(position).getId());
I have a DisplayStudentName.java file which is my main activity file. There is a model class which is used to get and set data and a MyCustomAdapter.java file which extends ArrayAdapter for listview functioning.
The checkbox is clicked but value is not added in the arraylist(named data; type String).
DisplayStudentName.java
public class DisplayStudentNames extends AppCompatActivity {
String myJSON;
private static final String TAG_RESULTS = "result";
private static final String TAG_ROLL = "RollNo";
private static final String TAG_NAME = "Name";
JSONArray peoples = null;
ListView list;
ArrayList<String> checkedValue;
Button b1;
MyCustomAdapter dataAdapter = null;
ArrayList<Student> personList=null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_student_names);
final Spinner sbranch = (Spinner) findViewById(R.id.branch);
final Spinner ssemester = (Spinner) findViewById(R.id.semester);
final Spinner ssubject = (Spinner) findViewById(R.id.edit_subject);
//String branch=sbranch.getSelectedItem().toString();
//String semester=ssemester.getSelectedItem().toString();
//String subject=ssubject.getSelectedItem().toString();
String branch = "cs";
String semester = "7";
String subject = "Soft Computing";
b1 = (Button) findViewById(R.id.submit);
list = (ListView) findViewById(R.id.listView);
new DataFetch().execute(branch, semester, subject);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Student student = (Student) parent.getItemAtPosition(position);
String Name = student.getName();
//String s=(String) ((TextView) view.findViewById(R.id.roll)).getText();
Toast.makeText(getApplicationContext(), "Clicked: " + Name, Toast.LENGTH_SHORT).show();
}
});
//submitAttendance();
}
class DataFetch extends AsyncTask<String, String, String> {
ArrayList<NameValuePair> params;
private ProgressDialog pDialog;
private String url_fetch_data = "http://192.168.1.4/AttendanceApp/fetch_data.php";
InputStream is = null;
String res = "";
protected void onPreExecute() {
super.onPreExecute();
}
protected String doInBackground(String... args) {
String branch = args[0];
String semester = args[1];
String subject1 = args[2];
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url_fetch_data);
params = new ArrayList<NameValuePair>(3);
params.add(new BasicNameValuePair("branch", branch));
params.add(new BasicNameValuePair("semester", semester));
params.add(new BasicNameValuePair("subject", subject1));
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
BufferedReader br = new BufferedReader(new InputStreamReader(is, "utf-8"), 8);
StringBuilder total = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
total.append(line);
}
String result = total.toString();
return result;
} catch (Exception e1) {
res = "error:" + e1.getMessage().toString();
e1.printStackTrace();
}
return res;
}
protected void onPostExecute(String httpResponse) {
myJSON = httpResponse;
showList();
}
}
protected void showList() {
try {
JSONObject jsonObj = new JSONObject(myJSON);
peoples = jsonObj.getJSONArray("result");
personList = new ArrayList<Student>();
for (int i = 0; i < peoples.length(); i++) {
Student student = new Student();
JSONObject c = peoples.getJSONObject(i);
String roll = c.getString(TAG_ROLL);
String name = c.getString(TAG_NAME);
student.setName(name);
student.setRollNo(roll);
personList.add(student);
}
dataAdapter = new MyCustomAdapter(this, R.layout.list_item, personList);
list.setAdapter(dataAdapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
MyCustomAdapter.java
public class MyCustomAdapter extends ArrayAdapter {
public ArrayList<Student> personList=null;
private Context context=null;
private static LayoutInflater inflater=null;
private ArrayList<String> data=null;
private View vi;
ViewHolder holder=null;
public MyCustomAdapter(Context context, int resource, ArrayList<Student> personList) {
super(context, resource, personList);
this.context=context;
this.personList=personList;
}
private class ViewHolder{
TextView roll;
TextView name;
CheckBox check;
}
public View getView(int position, View convertView, ViewGroup parent){
Log.v("ConvertView", String.valueOf(position));
if(convertView==null){
LayoutInflater vi = (LayoutInflater)context.getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
convertView = vi.inflate(R.layout.list_item, null);
holder=new ViewHolder();
holder.roll=(TextView)convertView.findViewById(R.id.roll);
holder.name=(TextView)convertView.findViewById(R.id.name);
holder.check=(CheckBox)convertView.findViewById(R.id.checkBox);
convertView.setTag(holder);
}
else{
holder=(ViewHolder)convertView.getTag();
}
Student student=personList.get(position);
holder.roll.setText(student.getRollno());
holder.name.setText(student.getName());
holder.check.setTag(student);
holder.check.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
data.add(holder.check.getText().toString());
} else {
data.remove(holder.check.getText().toString());
}
}
});
return convertView;
}
}
Student.java -Model class
public class Student {
String rollno;
String name;
Boolean checkbox;
public Student(){
}
public Student(String rollno, String name, Boolean status){
super();
this.rollno=rollno;
this.name=name;
this.checkbox=status;
}
public String getRollno(){
return rollno;
}
public void setRollNo(String rollno){
this.rollno=rollno;
}
public String getName(){
return name;
}
public void setName(String name){
this.name=name;
}
public Boolean isCheckbox(){
return checkbox;
}
public void setCheckbox(boolean checkbox) {
this.checkbox= checkbox;
}
Please tell me what is wrong with my code?
}
Whenever you are making any change in the dataset, call notifyDataSetChanged().
Thus it will be like this:
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
data.add(holder.check.getText().toString());
} else {
data.remove(holder.check.getText().toString());
}
notifyDataSetChanged();
}
I want to send Cus_id from postParamName to web server.
According to cus_id I want to fetch data from server and get it into listview.
I have no error in my code...but the code still not able to fetch data from server..
Plz look at my code...i have been working on this code since last two days. but I am not able to find the mistake
Point1.java
public class Points1 extends ListActivity implements FetchDataListener {
SessionManager session;
TextView tvCusPoints1, tvCusPoints2, tvcusName;
TextView bus_name;
TextView cus_points;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.points);
initView();
}
private void initView() {
session = new SessionManager(getApplicationContext());
// get user data from session
HashMap<String, String> user = session.getUserDetails();
// ID
String cus_id = user.get(SessionManager.KEY_ID);
ArrayList<NameValuePair> postParamName = new ArrayList<NameValuePair>();
postParamName.add(new BasicNameValuePair("cus_id", cus_id));
String url = "http://10.0.2.2/android_api_main/business_points.php";
FetchDataTask task = new FetchDataTask(this);
task.execute(url);
}
#Override
public void onFetchComplete(List<Application> data) {
// dismiss the progress dialog
// 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
}
}
Application.java
public class Application
{
private String bus_name;
private String cus_points;
public String getbus_name() {
return bus_name;
}
public void setbus_name(String bus_name) {
this.bus_name = bus_name;
}
public String getcus_points() {
return cus_points;
}
public void setcus_points(String cus_points) {
this.cus_points = cus_points;
}
}
ApplicationAdapter.java
public class ApplicationAdapter extends ArrayAdapter<Application> {
private List<Application> items;
public ApplicationAdapter(Context context, List<Application> items) {
super(context, R.layout.point_list_item, 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.point_list_item, null);
}
Application app = items.get(position);
if (app != null) {
TextView titleText = (TextView) v.findViewById(R.id.item_bname1);
TextView dlText = (TextView) v.findViewById(R.id.item_bpoint1);
if (titleText != null)
titleText.setText(app.getbus_name());
if (dlText != null)
dlText.setText(app.getcus_points());
}
return v;
}
}
FetchDataTask.java
public class FetchDataTask extends AsyncTask<String, Void, String> {
private final FetchDataListener listener;
private String msg;
String cus_id, responseString, success, bus_name, cus_points;
SessionManager session;
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();
responseString = EntityUtils.toString(entity);
// get response content and convert it to json string
} catch (IOException e) {
msg = "No Network Connection";
}
return responseString;
}
#Override
protected void onPostExecute(String sJson) {
try {
JSONObject json = new JSONObject(responseString);
JSONArray jArray = json.getJSONArray("customer");
List<Application> apps = new ArrayList<Application>();
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
bus_name = json_data.getString("bus_name");
cus_points = json_data.getString("cus_points");
success = json_data.getString("success");
Application app = new Application();
app.setbus_name(json.getString("bus_name"));
app.setcus_points(json.getString("cus_points"));
// add the app to apps
apps.add(app);
}
if (listener != null)
listener.onFetchComplete(apps);
} catch (JSONException e) {
msg = "Invalid response";
if (listener != null)
listener.onFetchFailure(msg);
return;
}
}
}
FetchDataListener.java
public interface FetchDataListener {
public void onFetchComplete(List<Application> data);
public void onFetchFailure(String msg);
}
Your FetchDataTask constructor accepts FetchDataTaskListener as parameter
public FetchDataTask(FetchDataListener listener) {
this.listener = listener;
}
But you have initialized it using activity's context
FetchDataTask task = new FetchDataTask(this);
Could you please check this.
You should set listener correctly, something like this
this.mListener = (FetchDataListener) activity
I've created an XML parser which populates a listView with data obtained from an XML file. The problem is for some reason the listView shows the same data over and over instead of unique data for each listView item.
I'm not sure exactly what is causing this issue - any insight is greatly appreciated.
Screenshot:
XML Data:
<response>
<cmd>getVideos</cmd>
<success>1</success>
<NumberOfVideos>4</NumberOfVideos>
<Videos>
<Video>
<VideoName>sample_iPod</VideoName>
<VideoDesc/>
<VideoUrl>
http://mobile.example.com/api/wp-content/uploads/sites/6/2014/01/api/1/06087297988b.m4v
</VideoUrl>
<VideoTags/>
</Video>
<Video>
<VideoName>sample_mpeg4</VideoName>
<VideoDesc/>
<VideoUrl>
http://mobile.example.com/api/wp-content/uploads/sites/6/2014/01/api/1/b5ed9e7100e2.mp4
</VideoUrl>
<VideoTags/>
</Video>
<Video>
<VideoName>sample_sorenson</VideoName>
<VideoDesc/>
<VideoUrl>
http://mobile.example.com/api/wp-content/uploads/sites/6/2014/01/api/1/2a8e64b24997.mov
</VideoUrl>
<VideoTags/>
</Video>
<Video>
<VideoName>sample_iTunes</VideoName>
<VideoDesc/>
<VideoUrl>
http://mobile.example.com/api/wp-content/uploads/sites/6/2014/01/api/1/6c7f65254aad.mov
</VideoUrl>
<VideoTags/>
</Video>
</Videos>
</response>
Example/Tutorial:
http://theopentutorials.com/tutorials/android/xml/android-simple-xml-sax-parser-tutorial/
SAXXMLHandler.java
public class SAXXMLHandler extends DefaultHandler {
private List<Cmd> videos;
private String tempVal;
// to maintain context
private Cmd cmd;
public SAXXMLHandler() {
videos = new ArrayList<Cmd>();
}
public List<Cmd> getResponse() {
return videos;
}
// Event Handlers
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
// reset
tempVal = "";
if (qName.equalsIgnoreCase("Video")) {
// create a new instance of cmd
cmd = new Cmd();
}
}
public void characters(char[] ch, int start, int length)
throws SAXException {
tempVal = new String(ch, start, length);
}
public void endElement(String uri, String localName, String qName)
throws SAXException {
if (qName.equalsIgnoreCase("videos")) {
// add it to the list
} else if (qName.equalsIgnoreCase("success")) {
cmd.setSuccess(tempVal);
} else if (qName.equalsIgnoreCase("numberofvideos")) {
cmd.setNumberOfVideos(tempVal);
} else if (qName.equalsIgnoreCase("videos")) {
cmd.setVideos(videos);
} else if (qName.equalsIgnoreCase("video")) {
cmd.setVideo(tempVal);
} else if (qName.equalsIgnoreCase("videoname")) {
cmd.setVideoName(tempVal);
} else if (qName.equalsIgnoreCase("videourl")) {
cmd.setVideoURL(tempVal);
videos.add(cmd); //You only need store an instance of your Cmd
}
}
}
CustomListViewAdapter.java
public class CustomListViewAdapter extends ArrayAdapter<Cmd> {
Activity context;
List<Cmd> videos;
public CustomListViewAdapter(Activity context, List<Cmd> videos) {
super(context, R.layout.list_item2, videos);
this.context = context;
this.videos = videos;
}
/*private view holder class*/
private class ViewHolder {
ImageView imageView;
TextView txtSuccess;
TextView txtCmd;
TextView txtPrice;
}
public Cmd getItem(int position) {
return videos.get(position);
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
LayoutInflater inflater = context.getLayoutInflater();
if (convertView == null) {
convertView = inflater.inflate(R.layout.list_item2, null);
holder = new ViewHolder();
holder.txtSuccess = (TextView) convertView.findViewById(R.id.success);
holder.txtCmd = (TextView) convertView.findViewById(R.id.cmd);
holder.txtPrice = (TextView) convertView.findViewById(R.id.price);
holder.imageView = (ImageView) convertView.findViewById(R.id.thumbnail);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
Cmd cmd = (Cmd) getItem(position);
holder.txtSuccess.setText(cmd.getSuccess());
holder.txtCmd.setText(cmd.getCmd());
// holder.imageView.setImageBitmap(cmd.getImageBitmap());
holder.txtPrice.setText(cmd.getVideoName() + "");
return convertView;
}
}
SAXParserAsyncTaskActivity.java
public class SAXParserAsyncTaskActivity extends Activity implements
OnClickListener, OnItemClickListener {
Button button;
ListView listView;
List<Cmd> videos = new ArrayList<Cmd>();
CustomListViewAdapter listViewAdapter;
static final String URL = "http://mobile.example.com/api/xmlrpc.php?cmd=getVideos&username=fake&password=credential";
public static final String LIBRARY = "Library";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.parser_main);
findViewsById();
button.setOnClickListener(this);
listView.setOnItemClickListener(this);
GetXMLTask task = new GetXMLTask(this);
task.execute(new String[] { URL });
}
private void findViewsById() {
button = (Button) findViewById(R.id.button);
listView = (ListView) findViewById(R.id.cmdList);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
}
#Override
public void onClick(View view) {
// GetXMLTask task = new GetXMLTask(this);
// task.execute(new String[] { URL });
}
// private inner class extending AsyncTask
private class GetXMLTask extends AsyncTask<String, Void, List<Cmd>> {
private Activity context;
public GetXMLTask(Activity context) {
this.context = context;
}
protected void onPostExecute(List<Cmd> videos) {
listViewAdapter = new CustomListViewAdapter(context, videos);
listView.setAdapter(listViewAdapter);
}
/*
* uses HttpURLConnection to make Http request from Android to download
* the XML file
*/
private String getXmlFromUrl(String urlString) {
StringBuffer output = new StringBuffer("");
try {
InputStream stream = null;
URL url = new URL(urlString);
URLConnection connection = url.openConnection();
HttpURLConnection httpConnection = (HttpURLConnection) connection;
httpConnection.setRequestMethod("GET");
httpConnection.connect();
if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
stream = httpConnection.getInputStream();
BufferedReader buffer = new BufferedReader(
new InputStreamReader(stream));
String s = "";
while ((s = buffer.readLine()) != null)
output.append(s);
}
} catch (Exception ex) {
ex.printStackTrace();
}
return output.toString();
}
#Override
protected List<Cmd> doInBackground(String... urls) {
List<Cmd> videos = null;
String xml = null;
for (String url : urls) {
xml = getXmlFromUrl(url);
InputStream stream = new ByteArrayInputStream(xml.getBytes());
videos = SAXXMLParser.parse(stream);
if ( videos == null) {
Toast.makeText(getApplicationContext(), "Videos is null!)",
Toast.LENGTH_LONG).show();
}
for (Cmd cmd : videos) {
String videoName = cmd.getVideoName();
// String getVideos = cmd.getVideos();
// String getVideo = cmd.getVideo();
// String getVideoURL = cmd.getVideoURL();
// String getNumberOfVideos = cmd.getNumberOfVideos();
//
// Bitmap bitmap = null;
// BitmapFactory.Options bmOptions = new BitmapFactory.Options();
// bmOptions.inSampleSize = 1;
//
// try {
// bitmap = BitmapFactory.decodeStream(
// new URL(videoName).openStream(), null,
// bmOptions);
// } catch (MalformedURLException e) {
// e.printStackTrace();
// } catch (IOException e) {
// e.printStackTrace();
// }
}
}
// stream.close();
return videos;
}
}
}
You are creating only one instance of Cmd() that is overriding itself, because you have only one <cmd> element.
Change:
if (qName.equalsIgnoreCase("cmd")) {
// create a new instance of cmd
cmd = new Cmd();
}
to:
if (qName.equalsIgnoreCase("Video")) {
// create a new instance of cmd
cmd = new Cmd();
}
You need to create an instance of Cmd() when your parser read every <Video> element.
and change your endElement(String uri, String localName, String qName) method to:
public void endElement(String uri, String localName, String qName)
throws SAXException {
if (qName.equalsIgnoreCase("videos")) {
// add it to the list
/*} else if (qName.equalsIgnoreCase("success")) {
cmd.setSuccess(tempVal);
} else if (qName.equalsIgnoreCase("numberofvideos")) {
cmd.setNumberOfVideos(tempVal);
} else if (qName.equalsIgnoreCase("videos")) {
cmd.setVideos(videos);
} else if (qName.equalsIgnoreCase("video")) {
cmd.setVideo(tempVal);*/
} else if (qName.equalsIgnoreCase("videoname")) {
cmd.setVideoName(tempVal);
} else if (qName.equalsIgnoreCase("videourl")) {
cmd.setVideoURL(tempVal);
videos.add(cmd); //You only need store an instance of your Cmd
}
}