Listview inside Cardview using RecyclerView - android

I want to add a dynamically loading listview inside cardviews arranged in a grid Layout that loads up dynamically according to data present. How can it be done?
All the listviews will be different according to data fetched from the links:
1) http://www.json-generator.com/api/json/get/bTARFsabKG?indent=2 (Used)
OR
2) http://www.json-generator.com/api/json/get/cnWvBVaGoO?indent=2
Supporting code for the same is as below:
Mainactivity.java
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
RecyclerView recyclerView;
Context context;
RecyclerView.Adapter recyclerView_Adapter;
RecyclerView.LayoutManager recyclerViewLayoutManager;
FoodItem foodItem;
ArrayList<FoodItem> items;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
foodItem = new FoodItem();
items = new ArrayList<FoodItem>();
new ApiFetchOrder().execute("");
context = getApplicationContext();
recyclerView = (RecyclerView) findViewById(R.id.recycler_view1);
}
public class ApiFetchOrder extends AsyncTask<String, Void, String> {
private String JsonResponse = null;
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
JsonResponse = null;
JSONArray jsonArray = null;
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
try {
URL url = new URL("http://www.json-generator.com/api/json/get/bTARFsabKG?indent=2");
Log.d("urlUpadteImage", String.valueOf(url));
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setConnectTimeout(30000);
urlConnection.setRequestMethod("GET");
Log.d("urlConnection", String.valueOf(urlConnection));
InputStream inputstream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputstream == null) {
return null;
}
reader = new BufferedReader(new InputStreamReader(inputstream));
String inputLine;
while ((inputLine = reader.readLine()) != null)
buffer.append(inputLine + "\n");
if (buffer.length() == 0) {
return null;
}
JsonResponse = buffer.toString();
jsonArray = new JSONArray(JsonResponse);
Log.v("JsonRes",jsonArray.getJSONObject(0).getJSONObject("foodItem").getJSONArray("item1").getString(0));
//Log.v("JsonResponse",JsonResponse);
int j=1;
while(j<=4) {
for (int i = 0; i < jsonArray.length(); i++) {
JSONArray arr = jsonArray.getJSONObject(i).getJSONObject("foodItem").getJSONArray("item" + j);
foodItem.setName(arr.getString(0));
foodItem.setQuantity(arr.getString(1));
Log.v("JsonArray", arr.getString(0)+arr.getString(1));
j++;
items.add(foodItem);
}
j++;
}
} catch (IOException | JSONException e) {
e.printStackTrace();
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
}
}
}
return null;
}
#Override
protected void onPostExecute(String s) {
//Change 3 to your choice because here 3 is the number of Grid layout Columns in each row.
recyclerViewLayoutManager = new GridLayoutManager(context,3);
recyclerView.setLayoutManager(recyclerViewLayoutManager);
recyclerView_Adapter = new RecyclerViewAdapter(context,items);
recyclerView.setAdapter(recyclerView_Adapter);
}
}
}
RecyclerViewAdapter.java
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.os.AsyncTask;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import org.json.JSONArray;
import org.json.JSONException;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {
ArrayList<FoodItem> values;
Context context1;
ItemsAdapter listViewAdapter;
FoodItem foodItem;
public RecyclerViewAdapter(Context context2,ArrayList<FoodItem> values2){
context1 = context2;
values= values2;
}
public static class ViewHolder extends RecyclerView.ViewHolder{
public ListView listView;
public ViewHolder(View v){
super(v);
listView = (ListView) v.findViewById(R.id.list);
}
}
#Override
public RecyclerViewAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType){
View view1 = LayoutInflater.from(context1).inflate(R.layout.item_view,parent,false);
listViewAdapter = new ItemsAdapter(context1,R.layout.items,values);
foodItem = new FoodItem();
return new ViewHolder(view1);
}
#Override
public void onBindViewHolder(ViewHolder Vholder, int position){
Vholder.listView.setAdapter(listViewAdapter);
}
#Override
public int getItemCount(){
return values.size();
}
}
ItemsAdapter.java
import android.annotation.SuppressLint;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.util.ArrayList;
public class ItemsAdapter extends ArrayAdapter<FoodItem> {
ArrayList<FoodItem> itemList;
LayoutInflater vi;
int Resource;
ViewHolder holder;
public ItemsAdapter(Context context, int resource , ArrayList<FoodItem> objects) {
super(context, resource , objects);
vi = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
Resource = resource;
itemList = objects;
}
#SuppressLint("SetTextI18n")
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
holder = new ViewHolder();
v = vi.inflate(Resource, null);
holder.itemName = (TextView) v.findViewById(R.id.itemName);
holder.itemQuantity = (TextView) v.findViewById(R.id.itemQuantity);
v.setTag(holder);
} else {
holder = (ViewHolder) v.getTag();
}
holder.itemName.setText(itemList.get(position).getName());
holder.itemQuantity.setText(itemList.get(position).getQuantity());
return v;
}
static class ViewHolder {
public TextView itemName;
public TextView itemQuantity;
}
}
FoodItem.java
public class FoodItem {
String Name,Quantity,TableNo;
public FoodItem(){}
public FoodItem(String name, String quantity, String tableNo) {
Name = name;
Quantity = quantity;
TableNo = tableNo;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getQuantity() {
return Quantity;
}
public void setQuantity(String quantity) {
Quantity = quantity;
}
public String getTableNo() {
return TableNo;
}
public void setTableNo(String tableNo) {
TableNo = tableNo;
}
}
Layout Files:
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:id="#+id/relativelayout">
<android.support.v7.widget.RecyclerView
android:id="#+id/recycler_view1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="vertical">
</android.support.v7.widget.RecyclerView>
</RelativeLayout>
item_view.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:id="#+id/cardview1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
card_view:cardElevation="7dp"
card_view:contentPadding="7dp"
card_view:cardCornerRadius="7dp"
card_view:cardMaxElevation="7dp"
>
<ListView
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</android.support.v7.widget.CardView>
</LinearLayout>
items.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/itemName"
tools:text="Item Name"
android:layout_width="0dp"
android:layout_weight="3"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/itemQuantity"
tools:text="Quantity"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content" />
</LinearLayout>

Related

ListView not getting populated from the Adapter

This app is used to fetch the books as JSON using Google Books API and on research I also found that the JSON data is loading fine and the Book Title, Author is parsed correctly and I tested that using toasts. But the listView is not showing up even from setting the listView with the adapter. What must be the error? The app also doesn't crash making it little difficult to troubleshoot. Thanks in advance!
Main Activity
package com.praveent.booklisting;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Scanner;
public class MainActivity extends AppCompatActivity {
public String rootUrl = "https://www.googleapis.com/books/v1/volumes";
public String queryParameter = "q";
Button search_button;
EditText search_string;
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.list_view);
search_button = (Button) findViewById(R.id.search_button);
search_string = (EditText) findViewById(R.id.search_string);
search_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String query = search_string.getText().toString();
ConnectivityManager connectivityManager
= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
if(activeNetworkInfo != null && activeNetworkInfo.isConnected()){
new BackgroundTask().execute(query);
}
else{
Toast.makeText(MainActivity.this, "Please switch on the internet!", Toast.LENGTH_SHORT).show();
}
}
});
}
public void populate(BookAdapter adapter){
listView.setAdapter(adapter);
}
public class BackgroundTask extends AsyncTask<String, JSONArray, String> {
#Override
protected String doInBackground(String... strings) {
String query = strings[0];
URL url = null;
Uri uri = Uri.parse(rootUrl).buildUpon().appendQueryParameter(queryParameter, query).build();
try {
url = new URL(uri.toString());
} catch (MalformedURLException e) {
e.printStackTrace();
}
String data = null;
try {
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = urlConnection.getInputStream();
Scanner scanner = new Scanner(in);
scanner.useDelimiter("\\A");
if(scanner.hasNext()){
data = scanner.next();
}
} catch (IOException e1) {
e1.printStackTrace();
}
return data;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
BookAdapter bookAdapter;
JSONObject jsonObject = null;
JSONArray jsonArray = null;
JSONObject jsonArrayObject = null;
JSONObject volumeInfo = null;
JSONArray authorInfo = null;
JSONObject imageInfo = null;
String imageUrl = null;
String bookTitle = null;
String bookAuthor = null;
try {
jsonObject = new JSONObject(s);
jsonArray = jsonObject.getJSONArray("items");
ArrayList<Book> books= new ArrayList<Book>();
for(int i = 0; i <= jsonArray.length(); i++){
jsonArrayObject = jsonArray.getJSONObject(i);
volumeInfo = jsonArrayObject.getJSONObject("volumeInfo");
bookTitle = volumeInfo.getString("title");
authorInfo = volumeInfo.getJSONArray("authors");
bookAuthor = " ";
if (authorInfo != null){
bookAuthor = authorInfo.getString(0);
}
//imageInfo = volumeInfo.getJSONObject("imageLinks");
//imageUrl = imageInfo.getString("smallThumbnail");
books.add(new Book(bookTitle, bookAuthor));
Toast.makeText(MainActivity.this, bookAuthor, Toast.LENGTH_SHORT).show();
}
bookAdapter = new BookAdapter(MainActivity.this, books);
populate(bookAdapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
Book Adapter
package com.praveent.booklisting;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
public class BookAdapter extends ArrayAdapter<Book>{
Context c = null;
public BookAdapter(Context context, ArrayList<Book> books) {
super(context, 0, books);
c = context;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View listItemView = convertView;
if (listItemView == null) {
listItemView = LayoutInflater.from(getContext()).inflate(
R.layout.list_item, parent, false);
}
Book currentBook = getItem(position);
TextView bookTextView = (TextView) listItemView.findViewById(R.id.book_name);
bookTextView.setText(currentBook.getBookName());
TextView authorTextView = (TextView) listItemView.findViewById(R.id.book_author);
authorTextView.setText(currentBook.getAuthorName());
//ImageView coverImageView = (ImageView) listItemView.findViewById(R.id.cover_image);
//Picasso.with(c).load(currentBook.getImageURL()).into(coverImageView);
return listItemView;
}
}
Book Class
package com.praveent.booklisting;
public class Book {
private String bookName;
private String authorName;
private String imageURL;
public Book(String name, String author){
bookName = name;
authorName = author;
//imageURL = url;
}
public String getBookName() {
return bookName;
}
public String getAuthorName() {
return authorName;
}
public String getImageURL() {
return imageURL;
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_height="match_parent"
tools:context="com.praveent.booklisting.MainActivity">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="16dp"
android:id="#+id/search_string"
android:textAlignment="center"
android:gravity="center"
android:hint="#string/search_hint"/>
<Button
android:layout_width="match_parent"
android:id="#+id/search_button"
android:layout_height="wrap_content"
android:text="#string/search_button" />
<ListView
android:layout_width="fill_parent"
android:id="#+id/list_view"
android:layout_height="fill_parent">
</ListView>
</LinearLayout>
list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:padding="8dp"
android:layout_height="wrap_content">
<ImageView
android:layout_width="100dp"
android:layout_height="100dp"
android:id="#+id/cover_image"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="8dp"
android:layout_gravity="center"
android:orientation="vertical">
<TextView
android:id="#+id/book_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#000"
android:textSize="18sp"
android:textStyle="bold" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="16sp"
android:textColor="#000"
android:id="#+id/book_author"/>
</LinearLayout>
</LinearLayout>
On PostExecute Change
for(int i = 0; i <=jsonArray.length(); i++)
to for(int i = 0;i<jsonArray.length(); i++)
On list_item.xml change the text color to white
you need to call getCount() in adapter.
public class BookAdapter extends ArrayAdapter<Book>{
Context c = null;
ArrayList<Book> bookslist = new ArrayList();
public BookAdapter(Context context, ArrayList<Book> books) {
super(context, 0, books);
c = context;
bookslist = books;
}
#Override
public int getCount() {
return bookslist.size();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View listItemView = convertView;
if (listItemView == null) {
listItemView = LayoutInflater.from(getContext()).inflate(
R.layout.list_item, parent, false);
}
Book currentBook = getItem(position);
TextView bookTextView = (TextView) listItemView.findViewById(R.id.book_name);
bookTextView.setText(currentBook.getBookName());
TextView authorTextView = (TextView) listItemView.findViewById(R.id.book_author);
authorTextView.setText(currentBook.getAuthorName());
//ImageView coverImageView = (ImageView) listItemView.findViewById(R.id.cover_image);
//Picasso.with(c).load(currentBook.getImageURL()).into(coverImageView);
return listItemView;
}
}
Change your adapter to this
public class BookAdapter extends ArrayAdapter<Book> {
Context c = null;
private List<Book> bookList;
public BookAdapter(Context context, ArrayList<Book> books) {
super(context, 0, books);
c = context;
bookList = new ArrayList<>();
bookList = books;
}
#Override
public int getCount() {
return bookList.size();
}
#Nullable
#Override
public Book getItem(int position) {
return bookList.get(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View listItemView = convertView;
if (listItemView == null) {
listItemView = LayoutInflater.from(getContext()).inflate(
R.layout.list_item, parent, false);
}
Book currentBook = getItem(position);
TextView bookTextView = (TextView) listItemView.findViewById(R.id.book_name);
bookTextView.setText(currentBook.getBookName());
TextView authorTextView = (TextView) listItemView.findViewById(R.id.book_author);
authorTextView.setText(currentBook.getAuthorName());
//ImageView coverImageView = (ImageView) listItemView.findViewById(R.id.cover_image);
//Picasso.with(c).load(currentBook.getImageURL()).into(coverImageView);
return listItemView;
}
}
I checked your code Error is in the AsyncTask onPostExecute method, change your for loop condition to this
for(int i = 0; i < jsonArray.length(); i++)
It is now working.

Using button in custom listview

in my android project I am using a custom listview where all the values are retrieved from the server and displayed in the listview. I have a button along with the textview in the listview entries, now I want to functionality of the button to be like when I click it will take the value from any textview of the same group and display it in the alert box. I retrieved the data and displayed successfully but I'm not able crack how to use the button to get the textview values of the list.. Thanks in advance for any help... My codes are posted below.
This is my contact adapter class:
package com.example.sohan.doctor;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Sohan on 6/9/2016.
*/
public class ContactAdapter extends ArrayAdapter {
notification nt = new notification();
List list = new ArrayList();
View row;
ContactHolder contactHolder;
public ContactAdapter(Context context, int resource) {
super(context, resource);
}
public void add(List<Contacts> updatedList) {
list.clear();
list.addAll(updatedList);
notifyDataSetChanged();
}
#Override
public Object getItem(int position) {
return list.get(position);
}
#Override
public int getCount() {
return list.size();
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
row = convertView;
if(row==null){
LayoutInflater layoutInflater = (LayoutInflater)this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = layoutInflater.inflate(R.layout.view_symptom_layout,parent,false);
contactHolder = new ContactHolder();
contactHolder.Name =(TextView) row.findViewById(R.id.textView2);
contactHolder.Age =(TextView) row.findViewById(R.id.textView3);
contactHolder.Height =(TextView) row.findViewById(R.id.textView4);
contactHolder.Weight =(TextView) row.findViewById(R.id.textView5);
contactHolder.Symptom =(TextView) row.findViewById(R.id.textView6);
contactHolder.button = (Button) row.findViewById(R.id.button3);
contactHolder.button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String name;
name = nt.newList.get(position).getName(); // This is where I'm stucked.
Toast.makeText(getContext().getApplicationContext(), name+" is served ", Toast.LENGTH_LONG).show();
}
});
row.setTag(contactHolder);
}
else{
contactHolder = (ContactHolder)row.getTag();
}
Contacts contacts = (Contacts)this.getItem(position);
contactHolder.Name.setText("Name: "+contacts.getName());
contactHolder.Age.setText("Age: "+contacts.getAge());
contactHolder.Height.setText("Height: "+contacts.getHeight());
contactHolder.Weight.setText("Weight: "+contacts.getWeight());
contactHolder.Symptom.setText("Symptoms: "+contacts.getSymptom());
return row;
}
static class ContactHolder{
TextView Name;
TextView Age;
TextView Height;
TextView Weight;
TextView Symptom;
Button button;
}
}
And this is the class where I retrieve all the values from server and store it in listview:
package com.example.sohan.doctor;
import android.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Sohan on 6/25/2016.
*/
public class notification extends Fragment implements AdapterView.OnItemSelectedListener{
public final static String Message = "Sohan";
View myView;
String selectedCity;
Context myContext;
String jsonResult;
JSONObject jsonObject;
JSONArray jsonArray;
String JSON_String;
ContactAdapter contactAdapter;
ListView listView;
List<Contacts> newList;
Button button;
String send;
public View onCreateView(final LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
myView = inflater.inflate(R.layout.notification, container, false);
myContext = inflater.getContext();
contactAdapter = new ContactAdapter(myContext, R.layout.view_symptom_layout);
listView = (ListView)myView.findViewById(R.id.listView);
listView.setAdapter(contactAdapter);
retrieveInfo ri = new retrieveInfo();
ri.execute();
return myView;
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
class retrieveInfo extends AsyncTask<Void, Void, String> { // send data to server
String myUrl;
protected void onPreExecute() {
myUrl ="httP://myserver.com"; // change php script
}
protected String doInBackground(Void... args) {
String city;
String result = null;
JSONArray jsonArray = null;
try{
URL url = new URL(myUrl);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
// String data_to_send = URLEncoder.encode("city", "UTF-8")+"="+URLEncoder.encode(city,"UTF-8");
//bufferedWriter.write(data_to_send);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream is = httpURLConnection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
while ((JSON_String = reader.readLine()) != null)
{
sb.append(JSON_String+"\n");
}
reader.close();
httpURLConnection.disconnect();
is.close();
return sb.toString().trim();
}catch(MalformedURLException e){
e.printStackTrace();
}catch(IOException f){
f.printStackTrace();
}
return null;
}
protected void onPostExecute(String result) {
jsonResult = result;
parseJSON(jsonResult);
}
}
public void parseJSON(String json){
Contacts contacts=null;
try {
jsonObject = new JSONObject(json);
jsonArray = jsonObject.getJSONArray("patient");
int count = 0;
String name,age,height,weight,symptom;
newList = new ArrayList<Contacts>();
while (count < jsonArray.length()) {
JSONObject jo = jsonArray.getJSONObject(count);
name = jo.getString("Name"); // data's are send to store in and print in listview
age = jo.getString("Age");
height = jo.getString("Height");
weight = jo.getString("Weight");
symptom = jo.getString("Symptom");
contacts = new Contacts(name,age,height,weight,symptom);
newList.add(contacts); // data are stored in the newlist array
count++;
}
contactAdapter.add(newList); // the newlist array are send to add in the listview
} catch (Exception e) {
e.printStackTrace();
}
}
}
You can make some more changes like following.
ContactAdapter extends ArrayAdapter<Contacts>
List<Contacts> list = new ArrayList<Contacts>();
And this line:
String name,age,height,weight,symptom;
You should put in while loop with initialize as null ""
name = nt.newList.get(position).getName();
I think it should be:
name = list.get(position).getName();
You cam also read this article:
ListView with Add and Delete Buttons in each Row in android

JSON not loading into listview correctly - Android

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;
}

Custom adapter getting a NullPointerException with Inflator

I have an adapter that gets a list of items from an API and then puts it in a listview. This is the first time that Im working with adapters and list views and so far Im struggling quite a lot!
Why am I getting this error? Is my context wrong or something?
package com.example.tvrplayer;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
public class HiddenChannelsListAdapter extends BaseAdapter {
private Context mContext;
private ArrayList mItems;
private LayoutInflater mInflater;
public HiddenChannelsListAdapter(Context ctx, ArrayList list) {
mItems = list;
mContext = ctx;
mInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return mItems.size();
}
#Override
public HashMap getItem(int position) {
return (HashMap) mItems.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
System.out.println("getView " + position + " " + convertView);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.channel_item, parent, false);
} else {
((TextView) convertView.findViewById(R.id.channel_text)).setText("Testing");
}
return convertView;
}
public static class ViewHolder {
public TextView textView;
}
}
Asyntask to get the items from the server:
package com.example.tvrplayer;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import android.view.View;
import android.widget.ListView;
class ChannelPair {
public ListView lv;
public ArrayList channelList;
public Context ctx;
}
public class ChannelHandler extends AsyncTask<Object, Integer, ChannelPair> {
#Override
protected ChannelPair doInBackground(Object... params) {
ChannelPair p = new ChannelPair();
String apiurl = (String) params[0];
String linkid = (String) params[1];
String username = (String) params[2];
String channelID = null;
View vw = (View) params[3];
ListView lv = (ListView) vw.findViewById(R.id.list);
p.lv = lv;
JSONArray channels;
ArrayList< HashMap < String, String > > channelList = new ArrayList < HashMap < String, String > > ();
try {
channels = Json.getJson(apiurl + "/rest/channel/"+ username +"/"+ linkid, "GET");
Log.i("CHANNELS", channels.toString());
for (int i=0; i < channels.length(); i++) {
JSONObject json_data = channels.getJSONObject(i);
String name = json_data.getString("Name");
String channelid = json_data.getString("ChannelID");
HashMap<String, String> channelObject = new HashMap<String, String>();
// if ( json_data.getString("ParentPath") == "" ) {
channelObject.put("id", channelid);
channelObject.put("name", name);
channelList.add(channelObject);
// }
}
Log.i("ROOT CHANNELS", channelList.toString());
p.channelList = channelList;
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return p;
}
#Override
protected void onPostExecute(final ChannelPair p) {
HiddenChannelsListAdapter adapter = new HiddenChannelsListAdapter(p.ctx, p.channelList);
p.lv.setAdapter(adapter);
}
}
The error is in this line:
HiddenChannelsListAdapter.java:28
mInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
The full error code:
java.lang.NullPointerException
at com.example.tvrplayer.HiddenChannelsListAdapter.<init>(HiddenChannelsListAdapter.java:28)
at com.example.tvrplayer.ChannelHandler.onPostExecute(ChannelHandler.java:71)
at com.example.tvrplayer.ChannelHandler.onPostExecute(ChannelHandler.java:1)
at android.os.AsyncTask.finish(AsyncTask.java:602)
at android.os.AsyncTask.access$600(AsyncTask.java:156)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:615)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4514)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:790)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:557)
at dalvik.system.NativeStart.main(Native Method)

OnItemClickListener in ListView not identifying click

I've searched and tried to implement different solutions to this problem but nothing has solved this issue. I have a custom listview class and when its called from my main activity the first time everything works as expected. Clicking on an item yield in moving to the next activity. However when I am in my new activity and call identical code for the OnItemClickListener it doesn't react to clicks. Any help in this would be great as I am stumped.
OCForumsAppActivity is my main activity, and then BothActivity is where my onItemClickListener isn't working.
OCForumsAppActivity.java:
package com.ocforums.application;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.htmlcleaner.TagNode;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;
import com.ocforums.application.R;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.widget.EditText;
public class OCForumsAppActivity extends Activity {
//private MyCustomAdapter mAdapter;
public String md5(String s) {
try {
// Create MD5 Hash
MessageDigest digest = java.security.MessageDigest.getInstance("MD5");
digest.update(s.getBytes());
byte messageDigest[] = digest.digest();
// Create Hex String
StringBuffer hexString = new StringBuffer();
for (int i=0; i<messageDigest.length; i++)
hexString.append(Integer.toHexString(0xFF & messageDigest[i]));
return hexString.toString();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return "";
}
public void loginfunc(String un,String pwd) {
try {
String pmd5sum = md5(pwd);
//HttpClient client = new DefaultHttpClient();
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpget = new HttpGet("https://portal.sun.com/portal/dt");
HttpResponse response = client.execute(httpget);
HttpEntity entity = response.getEntity();
List<Cookie> cookies = client.getCookieStore().getCookies();
String postURL = "http://www.overclockers.com/forums/login.php?do=login";
HttpPost post = new HttpPost(postURL);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("vb_login_username", un));
params.add(new BasicNameValuePair("vb_login_md5sumpassword", pmd5sum));
params.add(new BasicNameValuePair("cookieuser","1"));
UrlEncodedFormEntity ent = new UrlEncodedFormEntity(params,HTTP.UTF_8);
post.setEntity(ent);
response = client.execute(post);
entity = response.getEntity();
cookies = client.getCookieStore().getCookies();
if (entity != null) {
Log.i("RESPONSE",EntityUtils.toString(entity));
}
client.getConnectionManager().shutdown();
} catch (Exception e) {
e.printStackTrace();
}
}
/* private class MyCustomAdapter extends BaseAdapter {
private ArrayList mData = new ArrayList();
private LayoutInflater mInflater;
public MyCustomAdapter() {
mInflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public void addItem(final List<List<String>> output2d) {
mData.add(output2d);
notifyDataSetChanged();
}
public int getCount() {
return mData.size();
}
public String getItem(int position) {
return (String) mData.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
System.out.println("getView " + position + " " + convertView);
ViewHolder holder = null;
if (convertView == null) {
convertView = mInflater.inflate(R.id.listView1, null);
holder = new ViewHolder();
holder.textView = (TextView)convertView.findViewById(R.id.listView1);
convertView.setTag(holder);
} else {
holder = (ViewHolder)convertView.getTag();
}
holder.textView.setText((CharSequence) mData.get(position));
return convertView;
}
}
public static class ViewHolder {
public TextView textView;
}*/
public static String gethurl()
{
return OCForumsAppActivity.hurl;
}
public static void sethurl(String newh)
{
OCForumsAppActivity.hurl = newh;
}
public static void sethreflist(List<String> newlist)
{
hrefslist = newlist;
}
CustomListView lv = new CustomListView();
public static String hurl;
private ProgressDialog pd;
static List<String> hrefslist;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
pd = ProgressDialog.show(OCForumsAppActivity.this, "Working...", "request to server", true, false);
new ParseForums().execute("http://www.overclockers.com/forums/?styleid=23");
ListView list = (ListView)findViewById(R.id.listView1);
list.setOnItemClickListener(new OnItemClickListener(){
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Log.i("testing",hurl);
if(hurl.matches("(?i).*forumdisplay.*")){
Intent newActivity = new Intent(getBaseContext(), BothActivity.class);
startActivity(newActivity);
}
else if(hurl.matches("(?i).*showthread.php.*")) {
Intent newActivity = new Intent(getBaseContext(), ThreadActivity.class);
startActivity(newActivity);
}
else if(hrefslist == null){
Toast.makeText(getApplicationContext(), "Confused?", Toast.LENGTH_LONG).show();
//TODO add context menu for quote and reply
}
else{
Toast.makeText(getApplicationContext(), "Very Confused", Toast.LENGTH_LONG).show();
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.login:
final AlertDialog.Builder alert = new AlertDialog.Builder(this);
LinearLayout lila1= new LinearLayout(this);
lila1.setOrientation(1); //1 is for vertical orientation
final EditText usernametextbox = new EditText(this);
final EditText passwdtextbox = new EditText(this);
lila1.addView(usernametextbox);
lila1.addView(passwdtextbox);
alert.setView(lila1);
alert.setTitle("Login");
alert.setPositiveButton("Login", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String uname = usernametextbox.getText().toString().trim();
String passwd = usernametextbox.getText().toString().trim();
loginfunc(uname,passwd);
}
});
alert.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.cancel();
}
});
alert.show();
break;
case R.id.settings:
Toast.makeText(getApplicationContext(), "Perhaps one day...", Toast.LENGTH_SHORT).show();
break;
case R.id.UnansweredThreads:
hurl ="http://www.overclockers.com/forums/search.php?do=process&replyless=1&replylimit=0&exclude=78,124,37,167,186,186,187,21,144,18,179,150,181,182,183,11,164,95,151,123,27,28,29,30,31,32,142,170,33,36,67,62,63,65,11,19,200&nocache=0";
Intent newActivity = new Intent(getBaseContext(), ThreadActivity.class);
startActivity(newActivity);
break;
case R.id.MyPosts:
hurl = "http://www.overclockers.com/forums/search.php?do=getdaily&exclude=123&nocache=1";
Intent newActivity1 = new Intent(getBaseContext(), ThreadActivity.class);
startActivity(newActivity1);
break;
}
return true;
}
class ParseForums extends AsyncTask<String, Void, List<List<String>>> {
protected List<List<String>> doInBackground(String... arg) {
List<List<String>> combined2d = new ArrayList<List<String>>();
List<String> output = new ArrayList<String>();
List<String> hrefs = new ArrayList<String>();
try
{
HtmlHelper hh = new HtmlHelper(new URL(arg[0]));
List<TagNode> links = hh.getLinksByClass("forumtitle");
for (Iterator<TagNode> iterator = links.iterator(); iterator.hasNext();)
{
TagNode divElement = (TagNode) iterator.next();
output.add(divElement.getText().toString());
hrefs.add(divElement.getAttributeByName("href").toString());
}
combined2d.add(output);
combined2d.add(hrefs);
}
catch(Exception e)
{
e.printStackTrace();
}
return combined2d;
}
protected void onPostExecute(List<List<String>> output2d) {
pd.dismiss();
output2d.size();
Log.i("size",Integer.toString(output2d.get(0).size()));
Log.i("size",Integer.toString(output2d.get(1).size()));
ListView listview = (ListView) findViewById(R.id.listView1);
listview.setAdapter(lv.new MyCustomAdapter(OCForumsAppActivity.this, R.layout.row , output2d.get(0)));
hrefslist = output2d.get(1);
}
}
}
BothActivity.java:
package com.ocforums.application;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.htmlcleaner.TagNode;
import com.ocforums.application.CustomListView.MyCustomAdapter;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
public class BothActivity extends Activity{
List<String> foutput = new ArrayList<String>();
List<String> houtput = new ArrayList<String>();
CustomListView lv = new CustomListView();
String hurl;
List<String> hrefslist;
private ProgressDialog pd;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String qhurl = OCForumsAppActivity.gethurl();
String shurl = "http://www.overclockers.com/forums/"+qhurl+"&styleid=23";
pd = ProgressDialog.show(BothActivity.this, "Working...", "request to server", true, false);
new ParseBoth().execute(shurl);
Log.i("where ami?","back from execution");
ListView list = (ListView)findViewById(R.id.listView1);
list.setOnItemClickListener(new OnItemClickListener(){
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
hurl = hrefslist.get((int) id).replace("amp;","");
Toast.makeText(getApplicationContext(), hurl, Toast.LENGTH_LONG).show();
Log.i("testing",hurl);
if(hurl.matches("(?i).*forumdisplay.*")){
Toast.makeText(getApplicationContext(), hurl, Toast.LENGTH_LONG).show();
OCForumsAppActivity.sethurl(hurl);
BothActivity ba = new BothActivity();
ba.onCreate(null);
}
else if(hurl.matches("(?i).*showthread.php.*")) {
Intent newActivity = new Intent(getBaseContext(), ThreadActivity.class);
startActivity(newActivity);
}
else if(hrefslist == null){
Toast.makeText(getApplicationContext(), "Confused?", Toast.LENGTH_LONG).show();
//TODO add context menu for quote and reply
}
else{
Toast.makeText(getApplicationContext(), "Very Confused", Toast.LENGTH_LONG).show();
}
}
});
}
class ParseBoth extends AsyncTask<String, Void, List<List<String>>> {
protected List<List<String>> doInBackground(String... arg) {
List<List<String>> combined2d = new ArrayList<List<String>>();
List<String> output = new ArrayList<String>();
List<String> hrefs = new ArrayList<String>();
List<String> Toutput = new ArrayList<String>();
List<String> Threfs = new ArrayList<String>();
try
{
HtmlHelper hh = new HtmlHelper(new URL(arg[0]));
HtmlHelper hh2 = new HtmlHelper(new URL(arg[0]));
List<TagNode> links = hh.getLinksByClass("forumtitle");
List<TagNode> Tlinks = hh2.getLinksById("(?i).*thread.*");
for (Iterator<TagNode> iterator = links.iterator(); iterator.hasNext();)
{
TagNode divElement = (TagNode) iterator.next();
output.add(divElement.getText().toString());
hrefs.add(divElement.getAttributeByName("href").toString());
}
for (Iterator<TagNode> iterator = Tlinks.iterator(); iterator.hasNext();)
{
TagNode divElement = (TagNode) iterator.next();
Toutput.add(divElement.getText().toString());
Threfs.add(divElement.getAttributeByName("href").toString());
}
Log.i("size",Integer.toString(output.size()));
Log.i("size",Integer.toString(hrefs.size()));
Log.i("size",Integer.toString(Toutput.size()));
Log.i("size",Integer.toString(Threfs.size()));
combined2d.add(output);
combined2d.add(hrefs);
combined2d.add(Toutput);
combined2d.add(Threfs);
}
catch(Exception e)
{
e.printStackTrace();
}
return combined2d;
}
protected void onPostExecute(List<List<String>> output2d) {
pd.dismiss();
output2d.size();
foutput.addAll(output2d.get(0));
foutput.addAll(output2d.get(2));
houtput.addAll(output2d.get(1));
houtput.addAll(output2d.get(3));
Log.i("size",Integer.toString(foutput.size()));
setContentView(R.layout.main);
Log.i("where ami?","going");
ListView listview = (ListView) findViewById(R.id.listView1);
listview.setAdapter(lv.new MyCustomAdapter(getApplicationContext(), R.layout.row , foutput));
Log.i("where ami?","back");
hrefslist = houtput;
}
}
}
CustomListView.java:
package com.ocforums.application;
import java.util.List;
import android.app.Activity;
import android.app.ListActivity;
import android.content.Context;
import android.os.Bundle;
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 CustomListView extends ListActivity {
List<String> lists;
Context fcontext;
public void makelistview(List<String> list, Context context){
lists=list;
setListAdapter(new MyCustomAdapter(context, R.layout.row, lists));
}
public void onCreate(Bundle savedInstanceState) {
//super.onCreate(savedInstanceState);
}
public class MyCustomAdapter extends ArrayAdapter<String> {
public MyCustomAdapter(Context context, int textViewResourceId,
List<String> objects) {
super(context, textViewResourceId, objects);
fcontext = context;
// TODO Auto-generated constructor stub
lists=objects;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
TextView label=(TextView)row.findViewById(R.id.forumlist);
label.setText(lists.get(position));
ImageView icon=(ImageView)row.findViewById(R.id.icon);
if (lists.get(position).matches("AMD*")){
icon.setImageResource(R.drawable.forum_new);
}
else{
icon.setImageResource(R.drawable.forum_old);
}
return row;
}
}
}
row.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="wrap_content"
android:orientation="horizontal">
<ImageView
android:id="#+id/icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:focusable="false"
android:contentDescription="OCForums thread icon"
android:src="#drawable/forum_new" />
<TextView
android:id="#+id/forumlist"
android:focusable="false"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
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/listView1"
android:focusable="false"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
Try changing
<ListView
android:id="#+id/listView1"
android:focusable="false"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
</ListView>
To this..
<ListView
android:id="#+id/listView1"
android:focusable="true"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
</ListView>
I have experienced this same problem before. You need to change the root node for your row.xml file to RelativeLayout instead of LinearLayout. I'm not 100% sure why this works, but it did so for me.
Of course, you will also have to add a tag saying:
android:layout_toRightOf="#+id/icon"
inside your TextView node.

Categories

Resources