Populate listview from JSONArray android - java

Basically this question is an update for this question
Just to rewind again, this is the country_info.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="6dip" >
<LinearLayout
android:id="#+id/gambar_saja"
android:layout_width="150dp"
android:layout_height="160dp"
android:orientation="vertical">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/n1"/>
</LinearLayout>
<RelativeLayout
android:id="#+id/detail_country"
android:layout_width="match_parent"
android:layout_height="160dp"
android:layout_toRightOf="#+id/gambar_saja"
android:layout_toEndOf="#+id/gambar_saja"
android:orientation="vertical"
android:layout_marginLeft="4dp">
<TextView
android:id="#+id/code"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="TextView"
android:textSize="24sp"
android:textStyle="bold"
android:textAppearance="?android:attr/textAppearanceMedium"
android:layout_marginBottom="4dp"/>
<TextView
android:id="#+id/name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/code"
android:layout_below="#+id/code"
android:text="TextView"
android:textAppearance="?android:attr/textAppearanceMedium"
android:layout_marginBottom="4dp"/>
<TextView
android:id="#+id/continent"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/name"
android:layout_below="#+id/name"
android:text="TextView"
android:textSize="14sp"
android:textColor="#android:color/black"
android:textAppearance="?android:attr/textAppearanceMedium"
android:layout_marginBottom="4dp"/>
<TextView
android:id="#+id/region"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/continent"
android:layout_below="#+id/continent"
android:text="TextView"
android:textSize="14sp"
android:textColor="#android:color/black"
android:textAppearance="?android:attr/textAppearanceMedium"/>
</RelativeLayout>
</RelativeLayout>
and here is cari_studio.xml to populate the country_info into listview (listView1) :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#android:color/white">
<RelativeLayout
android:id="#+id/area"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#color/white"
android:orientation="horizontal" >
<TextView
android:id="#+id/isiArea"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:background="#drawable/text_selector"
android:gravity="center_vertical"
android:paddingBottom="10dp"
android:paddingLeft="35dp"
android:paddingRight="5dp"
android:paddingTop="10dp"
android:text="#string/area"
android:textColor="#color/black"
android:textSize="14sp"
android:visibility="visible"/>
<Spinner
android:id="#+id/textArea"
android:layout_marginRight="15dp"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:hint="#string/area"
android:textColor="#color/black"
android:inputType="text"
android:textSize="14sp"/>
</LinearLayout>
</RelativeLayout>
<RelativeLayout
android:id="#+id/list_area_studio"
android:layout_below="#+id/area"
android:layout_width="match_parent"
android:layout_height="fill_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content" android:padding="10dp"
android:text="#string/cari_studio" android:textSize="20sp" />
<EditText android:id="#+id/myFilter" android:layout_width="match_parent"
android:layout_height="wrap_content" android:ems="10"
android:hint="#string/studio_hint">
<requestFocus />
</EditText>
<ListView android:id="#+id/listView1" android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</LinearLayout>
</RelativeLayout>
<RelativeLayout
android:id="#+id/bottom_navigation_bar"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<RadioGroup
android:id="#+id/radiogroup"
android:layout_width="fill_parent"
android:layout_height="60dp"
android:layout_alignParentBottom="true"
android:orientation="horizontal"
android:background="#drawable/navbar_background"
>
<RadioButton
android:id="#+id/btnAll"
style="#style/navbar_button"
android:drawableTop="#drawable/navbar_allselector"
android:text="All"
/>
<RadioButton
android:id="#+id/btnPicture"
style="#style/navbar_button"
android:drawableTop="#drawable/navbar_pictureselector"
android:text="Pictures"
android:layout_marginLeft="5dp"
/>
<RadioButton
android:id="#+id/btnVideo"
style="#style/navbar_button"
android:drawableTop="#drawable/navbar_videoselector"
android:text="Videos"
android:layout_marginLeft="5dp"
/>
<RadioButton
android:id="#+id/btnFile"
style="#style/navbar_button"
android:drawableTop="#drawable/navbar_fileselector"
android:text="Files"
android:layout_marginLeft="5dp"
/>
<RadioButton
android:id="#+id/btnMore"
style="#style/navbar_button"
android:drawableTop="#drawable/navbar_moreselector"
android:text="More"
android:layout_marginLeft="5dp"
/>
</RadioGroup>
<LinearLayout
android:id="#+id/floatingmenu"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_marginLeft="30dp"
android:layout_marginRight="30dp"
android:background="#drawable/laysemitransparentwithborders"
android:orientation="vertical"
android:layout_marginBottom="-4dp"
android:visibility="gone"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingLeft="5dp"
android:paddingTop="15dp"
android:paddingBottom="15dp"
android:text="Contacts"
android:textColor="#ffffff"
android:textSize="16dp"
/>
<View
android:layout_width="fill_parent"
android:layout_height="1dp"
android:background="#ff999999"
/>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingLeft="5dp"
android:paddingTop="15dp"
android:paddingBottom="15dp"
android:text="Calendar"
android:textColor="#ffffff"
android:textSize="16dp"
/>
</LinearLayout>
</RelativeLayout>
</RelativeLayout>
and here is the Cari Studio Class to get JSONArray result (use post) and I already success get the result :
public class CariStudio extends Activity{
final Context context = this;
MyCustomAdapter dataAdapter = null;
RadioButton radioButton1, radioButton2, radioButton3, radioButton4, radioButton5;
TextView flexlocationid;
Spinner flexlocation;
JSONObject jsonobject;
JSONArray jsonarray;
ArrayList<String> provincelist;
ArrayList<ProvinceModel> province;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.cari_studio);
//Generate list View from ArrayList
new DownloadJSON().execute();
addListenerOnButton();
}
public void addListenerOnButton() {
Bundle extras = getIntent().getExtras();
final String token= extras.getString("TOKEN");
radioButton1 = (RadioButton) findViewById(R.id.btnAll);
radioButton1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(context, home.class);
intent.putExtra("TOKEN", token);
startActivity(intent);
}
});
radioButton2 = (RadioButton) findViewById(R.id.btnPicture);
radioButton2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(context, CariKelas.class);
intent.putExtra("TOKEN", token);
startActivity(intent);
}
});
radioButton3 = (RadioButton) findViewById(R.id.btnVideo);
radioButton3.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(context, CariStudio.class);
intent.putExtra("TOKEN", token);
startActivity(intent);
}
});
radioButton4 = (RadioButton) findViewById(R.id.btnFile);
radioButton4.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(context, HotStuff.class);
intent.putExtra("TOKEN", token);
startActivity(intent);
}
});
radioButton5 = (RadioButton) findViewById(R.id.btnMore);
radioButton5.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(context, MyAccount.class);
intent.putExtra("TOKEN", token);
startActivity(intent);
}
});
flexlocation = (Spinner) findViewById(R.id.textArea);
flexlocationid = (TextView) findViewById(R.id.isiArea);
}
private class SendfeedbackJob extends AsyncTask<String, Void, String> {
private static final String LOG_TAG = "CariStudio";
ProgressDialog dialog;
Bundle extras = getIntent().getExtras();
final String token= extras.getString("TOKEN");
#Override
protected String doInBackground(String... params) {
String areaid = params[0];
Utils.log("params 1:"+ areaid);
// do above Server call here
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("region_id", areaid ));
String responseString = null;
final String url_studio = Constant.URI_BASE_AVAILABLE_STUDIO+ "?token=" + token;
Utils.log("url studio:"+ url_studio);
try
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url_studio);
// no idea what this does :)
httppost.setEntity(new UrlEncodedFormEntity(postParameters));
// This is the line that send the request
HttpResponse response = httpclient.execute(httppost);
Utils.log("response:"+ response);
HttpEntity entity = response.getEntity();
String responseAsText = EntityUtils.toString(entity);
Utils.log("daftar isi studio: " + responseAsText);
JSONArray json = new JSONArray(responseAsText);
for (int i = 0; i < json.length(); i++) {
jsonobject = json.getJSONObject(i);
final String studio_name = jsonobject.getString("studio_name");
final String address = jsonobject.getString("address");
final String website = jsonobject.getString("website");
final String seo_url = jsonobject.getString("seo_url");
Utils.log("studio_name: " + studio_name);
runOnUiThread(new Runnable() {
public void run() {
ArrayList<Country> countryList = new ArrayList<Country>();
Country country = new Country(studio_name,address, "Website:"+ website,
"Fasilitas:"+ seo_url);
countryList.add(country);
//create an ArrayAdaptar from the String Array
dataAdapter = new MyCustomAdapter(context,
R.layout.country_info, countryList);
//enables filtering for the contents of the given ListView
ListView listView = (ListView) findViewById(R.id.listView1);
// Assign adapter to ListView
listView.setAdapter(dataAdapter);
listView.setTextFilterEnabled(true);
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// When clicked, show a toast with the TextView text
Country country = (Country) parent.getItemAtPosition(position);
Toast.makeText(getApplicationContext(),
country.getCode(), Toast.LENGTH_SHORT).show();
Intent intent = new Intent(context, checkin.class);
startActivity(intent);
}
});
EditText myFilter = (EditText) findViewById(R.id.myFilter);
myFilter.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
dataAdapter.getFilter().filter(s.toString());
}
});
}
});
}
}
catch (Exception e)
{
/*Toast.makeText(context,
"user not registered", Toast.LENGTH_SHORT).show();*/
Log.e(LOG_TAG, String.format("Error during login: %s", e.getMessage()));
}
return "processing";
}
protected void onPostExecute(Boolean result) {
//dialog.cancel();
}
}
// Download JSON file AsyncTask
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
// Locate the CariStudio Class
province = new ArrayList<ProvinceModel>();
// Create an array to populate the spinner
provincelist = new ArrayList<String>();
// JSON file URL address
final String url_flexlocation = Constant.URI_BASE_FLEXLOCATION;
Utils.log("url_flexlocation: " + url_flexlocation);
try {
// Locate the NodeList name
HttpGet httppost = new HttpGet(url_flexlocation);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
Utils.log("data: " + data);
JSONArray json = new JSONArray(data);
for (int i = 0; i < json.length(); i++) {
jsonobject = json.getJSONObject(i);
ProvinceModel worldpop = new ProvinceModel();
worldpop.setId(jsonobject.optString("flex_id"));
worldpop.setProvince(jsonobject.optString("name"));
province.add(worldpop);
// Populate spinner with province names
provincelist.add(jsonobject.optString("name"));
}
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
// Locate the spinner in cari_studio.xml
Spinner mySpinner = (Spinner) findViewById(R.id.textArea);
// Spinner adapter
mySpinner
.setAdapter(new ArrayAdapter<String>(CariStudio.this,
R.layout.spinner_white,
provincelist));
// Spinner on item click listener
mySpinner
.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0,
View arg1, int position, long arg3) {
// TODO Auto-generated method stub
// Locate the textviews in cari_studio.xml
TextView flexlocationid = (TextView) findViewById(R.id.isiArea);
// Set the text followed by the position
flexlocationid.setText(province.get(position).getId());
String areaid = flexlocationid.getText().toString();
Utils.log("area id:" + areaid);
SendfeedbackJob job = new SendfeedbackJob();
job.execute(areaid);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
}
private class MyCustomAdapter extends ArrayAdapter<Country> {
private ArrayList<Country> originalList;
private ArrayList<Country> countryList;
private CountryFilter filter;
public MyCustomAdapter(Context context, int textViewResourceId,
ArrayList<Country> countryList) {
super(context, textViewResourceId, countryList);
this.countryList = new ArrayList<Country>();
this.countryList.addAll(countryList);
this.originalList = new ArrayList<Country>();
this.originalList.addAll(countryList);
}
#Override
public Filter getFilter() {
if (filter == null){
filter = new CountryFilter();
}
return filter;
}
private class ViewHolder {
TextView code;
TextView name;
TextView continent;
TextView region;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
Log.v("ConvertView", String.valueOf(position));
if (convertView == null) {
LayoutInflater vi = (LayoutInflater)getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
convertView = vi.inflate(R.layout.country_info, null);
holder = new ViewHolder();
holder.code = (TextView) convertView.findViewById(R.id.code);
holder.name = (TextView) convertView.findViewById(R.id.name);
holder.continent = (TextView) convertView.findViewById(R.id.continent);
holder.region = (TextView) convertView.findViewById(R.id.region);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
Country country = countryList.get(position);
holder.code.setText(country.getCode());
holder.name.setText(country.getName());
holder.continent.setText(country.getContinent());
holder.region.setText(country.getRegion());
return convertView;
}
private class CountryFilter extends Filter
{
#Override
protected FilterResults performFiltering(CharSequence constraint) {
constraint = constraint.toString().toLowerCase();
FilterResults result = new FilterResults();
if(constraint != null && constraint.toString().length() > 0)
{
ArrayList<Country> filteredItems = new ArrayList<Country>();
for(int i = 0, l = originalList.size(); i < l; i++)
{
Country country = originalList.get(i);
if(country.toString().toLowerCase().contains(constraint))
filteredItems.add(country);
}
result.count = filteredItems.size();
result.values = filteredItems;
}
else
{
synchronized(this)
{
result.values = originalList;
result.count = originalList.size();
}
}
return result;
}
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint,
FilterResults results) {
countryList = (ArrayList<Country>)results.values;
notifyDataSetChanged();
clear();
for(int i = 0, l = countryList.size(); i < l; i++)
add(countryList.get(i));
notifyDataSetInvalidated();
}
}
}
}
the result that I got from Utils.log("daftar isi studio: " + responseAsText) :
[{"id":"8","studio_name":"Dodi fit","seo_url":"dodi-fit","address":"Komp. Pertanian Blok 5 No 3","postcode":"87473","area_phone":"","phone":"+62876543","area_phone_second":"","phone_second":"+62","website":"sucifir.com","region_id":"12","lokasi_id":"138","booking_window":"7","facebook":"dodifitfb","twitter":"dodifittw","how_to_get_there":"over there, by trun left and right","priority":"5"},{"id":"11","studio_name":"inu fit","seo_url":"inu-fit","address":"","postcode":"","area_phone":"","phone":"+6221324234","area_phone_second":"","phone_second":"","website":"","region_id":"11","lokasi_id":"137","booking_window":"0","facebook":"","twitter":"","how_to_get_there":"","priority":"5"},{"id":"5","studio_name":"Vstudio","seo_url":"vstudio","address":"Plaza Indonesia Ground Floor #541","postcode":"","area_phone":"","phone":"+6221453787","area_phone_second":"","phone_second":"","website":"www.jkiij.com","region_id":"12","lokasi_id":"137","booking_window":"0","facebook":"face","twitter":"twy","how_to_get_there":"","priority":"5"},{"id":"7","studio_name":"Infovendor","seo_url":"infovendor","address":"","postcode":"","area_phone":"","phone":"+6221123452","area_phone_second":"","phone_second":"","website":"www.kidsdngf.com","region_id":"12","lokasi_id":"135","booking_window":"1","facebook":"","twitter":"","how_to_get_there":"","priority":"5"},{"id":"12","studio_name":"Seleb Fitnes One","seo_url":"selebfitnesone-57","address":"Kelapa gading timur no 17","postcode":"","area_phone":"","phone":"+6221453777","area_phone_second":"","phone_second":"","website":"selebfirnes.com","region_id":"12","lokasi_id":"138","booking_window":"0","facebook":"","twitter":"","how_to_get_there":"","priority":"5"},{"id":"14","studio_name":"Riri Studio","seo_url":"riristudio-57","address":"Mall Kelapa Gading, Lt 5","postcode":"","area_phone":"","phone":"+6221459325","area_phone_second":"","phone_second":"","website":"riri-riri.com","region_id":"12","lokasi_id":"135","booking_window":"7","facebook":"","twitter":"","how_to_get_there":"","priority":"5"},{"id":"19","studio_name":"NF Studio","seo_url":"nf-studio","address":"Ruko Mediterania Blok A4 No 79Jalan Ahmad Yani Kav A5, Kota Bekasi","postcode":"13536","area_phone":"","phone":"+62265111222","area_phone_second":"","phone_second":"","website":"nfstudio.com","region_id":"11","lokasi_id":"137","booking_window":"7","facebook":"","twitter":"","how_to_get_there":"","priority":"5"}]
and the result that I got from looping Utils.log("studio_name: " + studio_name) are :
studio_name: Dodi fit
studio_name: inu fit
studio_name: Vstudio
studio_name: Infovendor
studio_name: Seleb Fitnes One
studio_name: Riri Studio
studio_name: NF Studio
It means I already got all of it use looping.
But the problem is the result did not populate into listview (it show as one one last result NF Studio, the other did not appear).
What I need is populate this into 4 texview from country_info (I disable imageview) :
String studio_name, address, website, seo_url
What is the correct code to show/populate that into listview?

Add the values into a List and pass it to the Adapter class of your ListView inside onPostExecute()

You don't need a thread, that's the whole point of async.
List View code is in the for loop
UI code belongs to PostExecute() not doInBackground()
You reinitialized the list inside of the loop
Try like this:
private class SendfeedbackJob extends AsyncTask<String, Void, String> {
private static final String LOG_TAG = "CariStudio";
private ArrayList<Country> countryList = new ArrayList<Country>();
ProgressDialog dialog;
Bundle extras = getIntent().getExtras();
final String token= extras.getString("TOKEN");
#Override
protected String doInBackground(String... params) {
String areaid = params[0];
Utils.log("params 1:"+ areaid);
// do above Server call here
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("region_id", areaid ));
String responseString = null;
final String url_studio = Constant.URI_BASE_AVAILABLE_STUDIO+ "?token=" + token;
Utils.log("url studio:"+ url_studio);
try
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url_studio);
// no idea what this does :)
httppost.setEntity(new UrlEncodedFormEntity(postParameters));
// This is the line that send the request
HttpResponse response = httpclient.execute(httppost);
Utils.log("response:"+ response);
HttpEntity entity = response.getEntity();
String responseAsText = EntityUtils.toString(entity);
Utils.log("daftar isi studio: " + responseAsText);
JSONArray json = new JSONArray(responseAsText);
for (int i = 0; i < json.length(); i++) {
jsonobject = json.getJSONObject(i);
final String studio_name = jsonobject.getString("studio_name");
final String address = jsonobject.getString("address");
final String website = jsonobject.getString("website");
final String seo_url = jsonobject.getString("seo_url");
Utils.log("studio_name: " + studio_name);
Country country = new Country(studio_name,address, "Website:"+ website,"Fasilitas:"+ seo_url);
countryList.add(country);
}
}
catch (Exception e)
{
/*Toast.makeText(context,
"user not registered", Toast.LENGTH_SHORT).show();*/
Log.e(LOG_TAG, String.format("Error during login: %s", e.getMessage()));
}
return "processing";
}
protected void onPostExecute(Boolean result) {
//dialog.cancel();
//create an ArrayAdaptar from the String Array
dataAdapter = new MyCustomAdapter(context,
R.layout.country_info, countryList);
//enables filtering for the contents of the given ListView
ListView listView = (ListView) findViewById(R.id.listView1);
// Assign adapter to ListView
listView.setAdapter(dataAdapter);
listView.setTextFilterEnabled(true);
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// When clicked, show a toast with the TextView text
Country country = (Country) parent.getItemAtPosition(position);
Toast.makeText(getApplicationContext(),
country.getCode(), Toast.LENGTH_SHORT).show();
Intent intent = new Intent(context, checkin.class);
startActivity(intent);
}
});
EditText myFilter = (EditText) findViewById(R.id.myFilter);
myFilter.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
dataAdapter.getFilter().filter(s.toString());
}
});
}
}

Related

Recyclview showing data while debug mode but not working in noraml run

I am working on android application and I am facing one problem. When I run my app then nothing showing in recycle view but when i check application in debug mode then data successfully showing in recycle view. I have checked my web service working fine and successfully giving data. How can i achieve this ?
ManageQuestionActivity,java
public class ManageQuestionActivity extends AppCompatActivity implements RecyclerView.OnScrollChangeListener{
private static final String TAG = MainActivity.class.getSimpleName();
private RecyclerView listView;
private RecyclerView.LayoutManager layoutManager;
private RecyclerView.Adapter adapter;
private QuestionsListAdapter listAdapter;
private List<QuestionsItem> timeLineItems;
private int requestCount = 1;
private ProgressDialog pDialog;
public static String id, message, token, encodedString;
int pageCount, totalPages;
SQLiteHandler db;
SessionManager session;
ConnectionDetector cd;
EditText edtSearch;
Boolean isInternetPresent = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_manage_question);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
listView = (RecyclerView) findViewById(R.id.list);
edtSearch = (EditText) findViewById(R.id.edtSearch);
listView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
listView.setLayoutManager(layoutManager);
//Adding an scroll change listener to recyclerview
listView.setOnScrollChangeListener(this);
// Progress dialog
pDialog = new ProgressDialog(this);
pDialog.setCancelable(false);
cd = new ConnectionDetector(this);
isInternetPresent = cd.isConnectingToInternet();
db = new SQLiteHandler(this);
// session manager
session = new SessionManager(this);
// Fetching user details from sqlite
HashMap<String, String> user = db.getUserDetails();
id = user.get("id");
token = user.get("token");
getData();
timeLineItems = new ArrayList<>();
adapter = new QuestionsListAdapter(timeLineItems, this);
listView.setAdapter(adapter);
}
public void getTimeLineData(final String token, final String page) {
String tag_string_req = "req_register";
// making fresh volley request and getting json
StringRequest strReq = new StringRequest(Request.Method.POST, AppConfig.questions, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
VolleyLog.d(TAG, "Response: " + response.toString());
if (response != null) {
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("status");
String message = jObj.getString("message");
if (error) {
totalPages = jObj.getInt("totalPages");
pageCount = jObj.getInt("page");
int limit = jObj.getInt("limit");
parseJsonFeed(response);
}
} catch (Exception e) {
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting params to register url
Map<String, String> params = new HashMap<String, String>();
params.put("my_token", token);
params.put("page", page);
params.put("limit", "20");
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
private void parseJsonFeed(String response) {
try {
JSONObject jsonObj = new JSONObject(response);
JSONArray feedArray = jsonObj.getJSONArray("data");
for (int i = 0; i < feedArray.length(); i++) {
JSONObject feedObj = (JSONObject) feedArray.get(i);
QuestionsItem item = new QuestionsItem();
item.setId(feedObj.getInt("id"));
item.setQuestion(feedObj.getString("question"));
String options = feedObj.getString("multi_ans_option");
String[] parts = options.split("\\|");
String part1 = parts[0];
String part2 = parts[1];
String part3 = parts[2];
String part4 = parts[3];
item.setAnsOne(part1);
item.setAnsTwo(part2);
item.setAnsThree(part3);
item.setAnsFour(part4);
item.setAnswer(feedObj.getString("answer"));
timeLineItems.add(item);
}
// notify data changes to list adapater
adapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
private void getData() {
//Adding the method to the queue by calling the method getDataFromServer
getTimeLineData(token, String.valueOf(requestCount));
//Incrementing the request counter
requestCount++;
}
//This method would check that the recyclerview scroll has reached the bottom or not
private boolean isLastItemDisplaying(RecyclerView recyclerView) {
if (recyclerView.getAdapter().getItemCount() != 0) {
int lastVisibleItemPosition = ((LinearLayoutManager) recyclerView.getLayoutManager()).findLastCompletelyVisibleItemPosition();
if (lastVisibleItemPosition != RecyclerView.NO_POSITION && lastVisibleItemPosition == recyclerView.getAdapter().getItemCount() - 1)
return true;
}
return false;
}
#Override
public void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
//Ifscrolled at last then
if (isLastItemDisplaying(listView)) {
//Calling the method getdata again
getData();
}
}
}
activity_manage_question.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">
<android.support.v7.widget.RecyclerView
android:id="#+id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:divider="#null" />
</LinearLayout>
QuestionsItem.java
public class QuestionsItem {
private int id;
private String question, ansOne, ansTwo, ansThree, ansFour, answer;
public QuestionsItem() {
}
public QuestionsItem(int id, String question, String ansOne, String ansTwo, String ansThree, String ansFour, String answer) {
super();
this.id = id;
this.question = question;
this.ansOne = ansOne;
this.ansTwo = ansTwo;
this.ansThree = ansThree;
this.ansFour = ansFour;
this.answer = answer;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getQuestion() {
return question;
}
public void setQuestion(String question) {
this.question = question;
}
public String getAnsOne() {
return ansOne;
}
public void setAnsOne(String ansOne) {
this.ansOne = ansOne;
}
public String getAnsTwo() {
return ansTwo;
}
public void setAnsTwo(String ansTwo) {
this.ansTwo = ansTwo;
}
public String getAnsThree() {
return ansThree;
}
public void setAnsThree(String ansThree) {
this.ansThree = ansThree;
}
public String getAnsFour() {
return ansFour;
}
public void setAnsFour(String ansFour) {
this.ansFour = ansFour;
}
public String getAnswer() {
return answer;
}
public void setAnswer(String answer) {
this.answer = answer;
}
}
QuestionsListAdapter.java
public class QuestionsListAdapter extends RecyclerView.Adapter<QuestionsListAdapter.ViewHolder> {
private List<QuestionsItem> timeLineItems;
String message, storyId, token, ide;
private Context context;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
ConnectionDetector cd;
Boolean isInternetPresent = false;
private ProgressDialog pDialog;
private SessionManager session;
private SQLiteHandler db;
int newPosition;
public QuestionsListAdapter(List<QuestionsItem> timeLineItems, Context context) {
super();
this.context = context;
this.timeLineItems = timeLineItems;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.questios_item, parent, false);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
pDialog = new ProgressDialog(context);
pDialog.setCancelable(false);
db = new SQLiteHandler(context);
// session manager
session = new SessionManager(context);
// Fetching user details from sqlite
HashMap<String, String> user = db.getUserDetails();
token = user.get("token");
//Getting the particular item from the list
QuestionsItem item = timeLineItems.get(position);
holder.txtQues.setText(item.getQuestion());
holder.txtAnsOne.setText(item.getAnsOne());
holder.txtAnsTwo.setText(item.getAnsTwo());
holder.txtAnsThree.setText(item.getAnsThree());
holder.txtAnsFour.setText(item.getAnsFour());
holder.txtAns.setText(item.getAnswer());
holder.btnEdit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final QuestionsItem m = timeLineItems.get(position);
String ide = String.valueOf(m.getId());
String ques = String.valueOf(m.getQuestion());
String Option1 = String.valueOf(m.getAnsOne());
String Option2 = String.valueOf(m.getAnsTwo());
String Option3 = String.valueOf(m.getAnsThree());
String Option4 = String.valueOf(m.getAnsFour());
String answer = String.valueOf(m.getAnswer());
Intent intent = new Intent(context, UpdateQuestionActivity.class);
intent.putExtra("id", ide);
intent.putExtra("ques", ques);
intent.putExtra("option1", Option1);
intent.putExtra("option2", Option2);
intent.putExtra("option3", Option3);
intent.putExtra("option4", Option4);
intent.putExtra("answer", answer);
context.startActivity(intent);
}
});
holder.btnDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final QuestionsItem m = timeLineItems.get(position);
newPosition = holder.getAdapterPosition();
ide = String.valueOf(m.getId());
alertBox();
}
});
}
#Override
public int getItemCount() {
return timeLineItems.size();
}
#Override
public int getItemViewType(int position)
{
return position;
}
class ViewHolder extends RecyclerView.ViewHolder{
TextView txtQues, txtAnsOne, txtAnsTwo, txtAnsThree, txtAnsFour, txtAns, btnEdit, btnDelete;
//Initializing Views
public ViewHolder(View itemView) {
super(itemView);
txtQues = (TextView) itemView.findViewById(R.id.txtQues);
txtAnsOne = (TextView) itemView.findViewById(R.id.txtAnsOne);
txtAnsTwo = (TextView) itemView.findViewById(R.id.txtAnsTwo);
txtAnsThree = (TextView) itemView.findViewById(R.id.txtAnsThree);
txtAnsFour = (TextView) itemView.findViewById(R.id.txtAnsFour);
txtAns = (TextView) itemView.findViewById(R.id.txtAns);
btnEdit = (TextView) itemView.findViewById(R.id.btnEdit);
btnDelete = (TextView) itemView.findViewById(R.id.btnDelete);
}
}
public void alertBox(){
AlertDialog.Builder builder = new AlertDialog.Builder(context);
//Uncomment the below code to Set the message and title from the strings.xml file
//builder.setMessage(R.string.dialog_message) .setTitle(R.string.dialog_title);
//Setting message manually and performing action on button click
builder.setMessage("Do you want to delete question ?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// Check for empty data in the form
cd = new ConnectionDetector(context);
isInternetPresent = cd.isConnectingToInternet();
if (isInternetPresent){
DeleteQuestion(token, ide);
}else {
final SweetAlertDialog alert = new SweetAlertDialog(context, SweetAlertDialog.WARNING_TYPE);
alert.setTitleText("No Internet");
alert.setContentText("No connectivity. Please check your internet.");
alert.show();
}
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// Action for 'NO' Button
dialog.cancel();
}
});
//Creating dialog box
AlertDialog alert = builder.create();
//Setting the title manually
alert.setTitle("Question");
alert.show();
}
private void DeleteQuestion(final String token, final String qid) {
// Tag used to cancel the request
String tag_string_req = "req_register";
pDialog.setMessage("Please wait ...");
showDialog();
StringRequest strReq = new StringRequest(Request.Method.POST, AppConfig.updateQues, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
hideDialog();
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("status");
if (error) {
String errorMsg = jObj.getString("message");
Toast.makeText(context, errorMsg, Toast.LENGTH_SHORT).show();
timeLineItems.remove(newPosition);
notifyItemRemoved(newPosition);
notifyItemRangeChanged(newPosition, timeLineItems.size());
} else {
// Error occurred in registration. Get the error
// message
String errorMsg = jObj.getString("message");
Toast.makeText(context, errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(context, "Oops something went wrong...", Toast.LENGTH_LONG).show();
hideDialog();
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting params to register url
Map<String, String> params = new HashMap<String, String>();
params.put("my_token", token);
params.put("qid", qid);
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
private void showDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
private void hideDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}
}
questios_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="5dp"
android:background="#color/white">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="5dp"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Question : "
android:textColor="#000000"
android:textSize="15sp" />
<TextView
android:id="#+id/txtQues"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="#dimen/feed_item_profile_name"
android:textStyle="bold" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="5dp"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Option 1 : "
android:textColor="#000000"
android:textSize="15sp" />
<TextView
android:id="#+id/txtAnsOne"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="#dimen/feed_item_profile_name"
android:textStyle="bold" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="5dp"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Option 2 : "
android:textColor="#000000"
android:textSize="15sp" />
<TextView
android:id="#+id/txtAnsTwo"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="#dimen/feed_item_profile_name"
android:textStyle="bold" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="5dp"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Option 3 : "
android:textColor="#000000"
android:textSize="15sp" />
<TextView
android:id="#+id/txtAnsThree"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="#dimen/feed_item_profile_name"
android:textStyle="bold" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="5dp"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Option 4 : "
android:textColor="#000000"
android:textSize="15sp" />
<TextView
android:id="#+id/txtAnsFour"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="#dimen/feed_item_profile_name"
android:textStyle="bold" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="5dp"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Answer : "
android:textColor="#000000"
android:textSize="15sp" />
<TextView
android:id="#+id/txtAns"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="#dimen/feed_item_profile_name"
android:textStyle="bold" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:weightSum="2">
<TextView android:id="#+id/btnEdit"
android:layout_width="0dp"
android:layout_height="30dp"
android:text="Edit"
android:background="#drawable/rounded_square_comment"
android:gravity="center"
android:textColor="#000000"
android:layout_weight="1"
android:textSize="15sp" />
<TextView
android:id="#+id/btnDelete"
android:layout_width="0dp"
android:layout_height="30dp"
android:text="Delete"
android:background="#drawable/rounded_square_comment"
android:gravity="center"
android:textColor="#000000"
android:layout_weight="1"
android:textSize="15sp" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
listView.setAdapter should not be here cut
timeLineItems = new ArrayList<>();
adapter = new QuestionsListAdapter(timeLineItems, this);
listView.setAdapter(adapter); // Cut from Here
And paste in this method:
private void parseJsonFeed(String response) {
try {
JSONObject jsonObj = new JSONObject(response);
JSONArray feedArray = jsonObj.getJSONArray("data");
for (int i = 0; i < feedArray.length(); i++) {
JSONObject feedObj = (JSONObject) feedArray.get(i);
QuestionsItem item = new QuestionsItem();
item.setId(feedObj.getInt("id"));
item.setQuestion(feedObj.getString("question"));
String options = feedObj.getString("multi_ans_option");
String[] parts = options.split("\\|");
String part1 = parts[0];
String part2 = parts[1];
String part3 = parts[2];
String part4 = parts[3];
item.setAnsOne(part1);
item.setAnsTwo(part2);
item.setAnsThree(part3);
item.setAnsFour(part4);
item.setAnswer(feedObj.getString("answer"));
timeLineItems.add(item);
listView.setAdapter(adapter); //Paste Here
}
// notify data changes to list adapater
adapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}

Searching a JSON data in Android using ListView

I am trying to search a JSON data fetched from a URL, but whenever the user types a search string the application crashes. How do I fix it?
Here is my code:
MainActivity.java
public class MainActivity extends AppCompatActivity {
private String TAG = MainActivity.class.getSimpleName();
private ProgressDialog pDialog;
private ListView lv;
private EditText filterText;
private ArrayAdapter<String> listAdapter;
// URL to get contacts JSON
private static String url = "http://210.213.86.195:14344/inventory/getallitemname";
ArrayList<HashMap<String, String>> itemList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
filterText = (EditText)findViewById(R.id.editText);
itemList = new ArrayList<>();
lv = (ListView) findViewById(R.id.list_item);
new GetItems().execute();
filterText.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
MainActivity.this.listAdapter.getFilter().filter(s);
}
#Override
public void afterTextChanged(Editable s) {
}
}
);
}
/**
* Async task class to get json by making HTTP call
*/
private class GetItems extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JSONArray items = jsonObj.getJSONArray("Data");
// looping through All Contacts
for (int i = 0; i < items.length(); i++) {
JSONObject c = items.getJSONObject(i);
String ItemCode = c.getString("ItemCode");
String ItemName = c.getString("ItemName");
// tmp hash map for single item
HashMap<String, String> item = new HashMap<>();
// adding each child node to HashMap key => value
item.put("ItemCode", ItemCode);
item.put("ItemName", ItemName);
// adding item to item list
itemList.add(item);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG)
.show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG)
.show();
}
});
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
MainActivity.this, itemList,
R.layout.list_item, new String[]{"ItemCode", "ItemName"}, new int[]{R.id.ItemCode,
R.id.ItemName});
lv.setAdapter(adapter);
}
}
}
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"
tools:context="com.example.jsonparser.MainActivity">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/editText"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<ListView
android:id="#+id/list_item"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="5dp"
android:layout_marginTop="10dp"
android:layout_below="#+id/editText"
android:layout_alignLeft="#+id/editText"
android:layout_alignStart="#+id/editText" />
</RelativeLayout>
list_item.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="vertical"
android:padding="#dimen/activity_horizontal_margin">
<TextView
android:id="#+id/ItemName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingBottom="2dip"
android:paddingTop="6dip"
android:textColor="#color/colorPrimaryDark"
android:textSize="16sp"
android:textStyle="bold" />
<TextView
android:id="#+id/ItemCode"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingBottom="2dip"
android:textColor="#color/colorAccent" />
</LinearLayout>
you have not initalized it anywhere in code:-
MainActivity.this.listAdapter
so default is null,in postExecute you are using local adapter variable.
Put
adapter = new ArrayAdapter<String>(this,
R.layout.list_view_rows, R.id.listview, ListofStringYouWantToDisplay);
below
lv = (ListView) findViewById(R.id.list_item);
hear - ListofStringYouWantToDisplay is String[] or ArrayList you want to display
Your problem is you not initializing adapter before use

How can I put drawable image into gridview?

I have a gridview with 5 columns, how could add in column 4 and 5, images that I have in drawable folder? The problem is that being a String arraylist not catch me drawable because it is an integer.
This is my XML:
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/scrolView"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="wrap_content"
android:orientation="vertical">
<GridView
android:id="#+id/Grid"
android:numColumns="5"
android:stretchMode="columnWidth"
android:layout_width="match_parent"
android:gravity="center"
android:columnWidth="120dp"
android:verticalSpacing="10dp"
android:horizontalSpacing="10dp"
android:layout_height="2000dp"
android:layout_marginTop="10dp"
android:layout_marginLeft="30dp"></GridView>
</LinearLayout>
This is the java code where I call carrito.xml, and i make the listview. This list view is filled with a String array.
public class carrito extends Fragment {
protected Context context;
private int numComandesCarrito;
private String[][] CarritoProductes;
private double Total;
DecimalFormat precision = new DecimalFormat("0.00");
NumberFormat formatter = NumberFormat.getCurrencyInstance();
String output = formatter.format(Total);
public carrito(){
}
public void setContext (Context context){
this.context = context;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
int i, i2;
numComandesCarrito = ((MainActivity) context).getNumComandesCarrito();
// Toast.makeText(context, Integer.toString(numComandesCarrito), Toast.LENGTH_LONG).show();
CarritoProductes = ((MainActivity) context).getCarritoProductes();
Total = 0;
ArrayList<String> lineasPedido = new ArrayList<String>();
ArrayList<Integer> itemsimg = new ArrayList( );
//Afegim la capçalera de la grid
lineasPedido.add("Plat");
lineasPedido.add("Quantitat");
lineasPedido.add("Preu");
for (i= 0; i < numComandesCarrito; i++){
for (i2 = 0; i2<3; i2++){
if (i2 == 2) {
lineasPedido.add(precision.format(Double.parseDouble(CarritoProductes[i2][i])) + " €");
Total = Total + Double.parseDouble(CarritoProductes[i2][i]);
}
else{
lineasPedido.add(CarritoProductes[i2][i]);
}
}
itemsimg.add(R.drawable.botonmenos);
}
lineasPedido.add("");
lineasPedido.add("");
lineasPedido.add("Total: " + (precision.format(Total)) + " €");
View rootView = inflater.inflate(R.layout.carrito, container, false);
GridView grdView = (GridView)rootView.findViewById(R.id.grdComanda);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this.getActivity(), android.R.layout.simple_list_item_1, lineasPedido);
grdView.setAdapter(adapter);
return rootView;
}
You have to use custom adapter to put image in gridview
activity.xml
<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" >
<GridView
android:id="#+id/gridView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:horizontalSpacing="5dp"
android:numColumns="2"
android:verticalSpacing="5dp" >
</GridView>
</RelativeLayout>
row.xml
<?xml version="1.0" encoding="UTF-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/layoutbg"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="250dp"
android:gravity="center"
android:orientation="horizontal" >
<ImageView
android:id="#+id/img"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:scaleType="fitXY"
android:src="#drawable/ic_launcher" />
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="50dp"
android:layout_alignParentBottom="true"
android:gravity="center"
android:orientation="horizontal" >
<TextView
android:id="#+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="left"
android:paddingLeft="15dp"
android:text="TextView" />
<TextView
android:id="#+id/num"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="right"
android:paddingRight="15dp"
android:text="TextView" />
</LinearLayout>
</RelativeLayout>
</RelativeLayout>
FriendAdapter.java
public class FriendAdapter extends ArrayAdapter<FriendBean>{
private Context mCtx;
private ArrayList<FriendBean> items = new ArrayList<FriendBean>();
private ViewHolder mHolder;
ImageLoader imgLoader = new ImageLoader(mCtx);
public LayoutInflater inflater;
int loader = R.drawable.loader;
public FriendAdapter(Context context, int textViewResourceId, ArrayList<FriendBean> items) {
super(context, textViewResourceId, items);
this.items = items;
this.mCtx = context;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater) mCtx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v=vi.inflate(R.layout.row, null);
mHolder=new ViewHolder();
mHolder.mImage=(ImageView)v.findViewById(R.id.img);
mHolder.mName=(TextView)v.findViewById(R.id.name);
mHolder.mPh=(TextView)v.findViewById(R.id.num);
mHolder.mlayoutbg=(RelativeLayout)v.findViewById(R.id.layoutbg);
v.setTag(mHolder);
}
else{
mHolder=(ViewHolder)v.getTag();
}
imgLoader.DisplayImage(items.get(position).getImage(), loader, mHolder.mImage);
//mHolder.mImage.setBackgroundResource(items.get(position).getImage());
mHolder.mName.setText(items.get(position).getName());
mHolder.mPh.setText(items.get(position).getPh());
mHolder.mlayoutbg.setBackgroundColor(Color.GREEN);
// if(position%3==1){
// mHolder.mlayoutbg.setBackgroundColor(Color.GRAY);
// }else if(position%3==2){
// mHolder.mlayoutbg.setBackgroundColor(Color.WHITE);
// }else{
// mHolder.mlayoutbg.setBackgroundColor(Color.YELLOW);
// }
return v;
}
public class ViewHolder {
public ImageView mImage;
public TextView mName;
public TextView mPh;
public RelativeLayout mlayoutbg;
}
}
FriendBean.java
package com.example.bean;
public class FriendBean {
private String Image;
private String name;
private String ph;
private String des;
public FriendBean(String Image, String name, String ph, String des) {
this.Image = Image;
this.name = name;
this.ph = ph;
this.des = des;
}
public String getImage() {
return Image;
}
public void setImage(String image) {
Image = image;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPh() {
return ph;
}
public void setPh(String ph) {
this.ph = ph;
}
public String getDes() {
return des;
}
public void setDes(String des) {
this.des = des;
}
}
MainActivity.java
public class MainActivity extends Activity {
private GridView mList;
private ArrayList<FriendBean> arr = new ArrayList<FriendBean>();
private FriendAdapter friendAdapter;
String friend_name, friend_phone, url, des;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mList = (GridView) findViewById(R.id.gridView1);
StringBuffer sb = new StringBuffer();
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(getAssets().open(
"gridarray.json")));
String temp;
while ((temp = br.readLine()) != null)
sb.append(temp);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} finally {
try {
br.close(); // stop reading
} catch (IOException e) {
e.printStackTrace();
}
}
String myjsonstring = sb.toString();
try {
JSONObject obj = new JSONObject(myjsonstring);
JSONArray jsonarray = obj.getJSONArray("json");
Log.e("Length", "" + jsonarray.length());
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject jsonObj = jsonarray.getJSONObject(i);
friend_name = jsonObj.getString("friend_name");
friend_phone = jsonObj.getString("friend_phone");
url = jsonObj.getString("image_url");
des = jsonObj.getString("des");
FriendBean bean = new FriendBean(url, friend_name, friend_phone,
des);
arr.add(bean);
Log.e("u", url);
Log.e("friend_name", friend_name);
Log.e("friend_phone", friend_phone);
}
friendAdapter = new FriendAdapter(MainActivity.this, R.layout.row, arr);
mList.setAdapter(friendAdapter);
mList.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "Clicked on " + arg2,
Toast.LENGTH_SHORT).show();
Intent i = new Intent(getApplicationContext(), NewPage.class);
i.putExtra("friend_name", arr.get(arg2).getName());
i.putExtra("friend_phone", arr.get(arg2).getPh());
i.putExtra("url", arr.get(arg2).getImage());
i.putExtra("des", arr.get(arg2).getDes());
startActivity(i);
}
});
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
gridarray.json (put it in asset folder)
{ "json" : [ { "image_url" : "http://www.ogmaconceptions.com/demo/NewsFeed/app_images/twitter_main.png",
"friend_name" : "Madhumoy",
"friend_phone" : "123",
"des" : "Hi I'm Madhumoy"
},
{ "image_url" : "http://www.ogmaconceptions.com/demo/NewsFeed/app_images/twitter_main.png",
"friend_name" : "Sattik",
"friend_phone" : "123",
"des" : "Hi I'm Sattik"
},
{ "image_url" : "http://www.ogmaconceptions.com/demo/NewsFeed/app_images/twitter_main.png",
"friend_name" : "Koushik",
"friend_phone" : "123",
"des" : "Hi I'm Koushik"
},
{ "image_url" : "http://www.ogmaconceptions.com/demo/NewsFeed/app_images/twitter_main.png",
"friend_name" : "Himanshu",
"friend_phone" : "123",
"des" : "Hi I'm Himanshu"
},
{ "image_url" : "http://www.ogmaconceptions.com/demo/NewsFeed/app_images/twitter_main.png",
"friend_name" : "Sandy",
"friend_phone" : "123",
"des" : "Hi I'm Sandy"
}
] }
Hope this will work..
Maybe try something like this? The user comments seem to be positive for the most part. http://www.compiletimeerror.com/2013/02/display-images-in-gridview.html#.VRF2I2NTf5w

How to use ChrisBanes' ActionBar-PullToRefresh library with Tab view at bottom in activity

I am trying to use Chris Banes' library Actionbar-PullToRefresh. It can be found here.
I am using Tabs at bottom of screen in my app. as you can see in screen shot.
I read through the sample code. He says that all you have to do is, wrap your refreshable view in a PullToRefreshLayout like this: How do i integrate it into my app.
public class MainActivity extends Activity implements OnTabChangeListener {
private TabHost mTabHost;
public static final String TAB_1 = "Open";
public static final String TAB_2 = "Approved";
public static final String TAB_3 = "Decline";
private int mCurrentTab;
public String result;
Vector<String> msgvector = new Vector<String>();
Vector<String> usernamevector = new Vector<String>();
Vector<String> feedIdvector = new Vector<String>();
Vector<String> userIdvector = new Vector<String>();
ListView listview,listview1,listview2;
private ProgressDialog simpleWaitDialog;
List<Rowfeeds> rowfeedlist;
public String result2;
public String result3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTabHost = (TabHost) findViewById(android.R.id.tabhost);
listview = (ListView)findViewById(R.id.tab_1);
listview1 = (ListView)findViewById(R.id.tab_2);
listview2 = (ListView)findViewById(R.id.tab_3);
new Feedsdata().execute();
setupTabs();
mTabHost.setOnTabChangedListener(this);
mTabHost.setCurrentTab(mCurrentTab);
}
private class Feedsdata extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
try {
Log.i("doInBackground", "doInBackground");
HttpClient hc = new DefaultHttpClient();
HttpPost postMethod = new HttpPost("http://192.168.21.74/mynetwork/formapi/top_feeds");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("from", "0"));
nameValuePairs.add(new BasicNameValuePair("to", "10"));
postMethod.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse rp = hc.execute(postMethod);
if (rp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
result = EntityUtils.toString(rp.getEntity());
Log.v("suggestion_data", "" + result);
JSONArray jsonary = new JSONArray(result);
for (int i = 0; i < jsonary.length(); i++) {
//Log.v("jsonary.length", "" +jsonary.length());
String sr = ""+jsonary.getJSONObject(i);
//Log.v("sr", "" +sr);
JSONObject jobj = new JSONObject(sr);
Log.v("======================", "=================" );
Log.v("feed_id", "" +jobj.getString("feed_id"));
Log.v("feed_message", "" +jobj.getString("feed_message"));
Log.v("user_id", "" +jobj.getString("user_id"));
Log.v("username", "" +jobj.getString("username"));
Log.v("======================", "=================" );
msgvector.add(""+jobj.getString("feed_message").toString().trim());
usernamevector.add("" +jobj.getString("username").toString().trim());
feedIdvector.add("" +jobj.getString("feed_id").toString().trim());
userIdvector.add("" +jobj.getString("user_id").toString().trim());
}
//for (int i = 0; i < feedIdvector.size(); i++) {
//Log.v("feedIdvector", "" +feedIdvector.elementAt(i));
//}
}else{
Log.d("JSON", "StatusCode "+rp.getStatusLine().getStatusCode());
}
} catch (Exception e) {
// TODO Auto-generated catch block
Log.i("AsyncTaskException", e.toString());
}
Log.i("popularAsyncTaskException", e.toString());
}
return null;
}
#Override
protected void onPreExecute() {
Log.i("Async-Example", "onPreExecute Called");
simpleWaitDialog = ProgressDialog.show(MainActivity.this,"Wait", "Downloading feeds");
}
#Override
protected void onPostExecute(String result) {
rowfeedlist = new ArrayList<Rowfeeds>();
for (int i = 0; i < msgvector.size(); i++) {
Rowfeeds rowfeeds = new Rowfeeds(msgvector.elementAt(i),usernamevector.elementAt(i),feedIdvector.elementAt(i));
rowfeedlist.add(rowfeeds);
}
Customfeedadapter feedadapter = new Customfeedadapter(getApplicationContext(),R.layout.feeds,rowfeedlist
,feedIdvector,userIdvector);
listview.setAdapter(feedadapter);
simpleWaitDialog.dismiss();
}
private void setupTabs() {
mTabHost.setup(); // you must call this before adding your tabs!
mTabHost.addTab(newTab(TAB_1, R.id.tab_1));
mTabHost.addTab(newTab(TAB_2, R.id.tab_2));
mTabHost.addTab(newTab(TAB_3, R.id.tab_3));
}
private TabSpec newTab(String tag, int tabContentId) {
Log.i("tag", tag);//fff498
Log.i("tabContentId", ""+tabContentId);//fff498
TabSpec spec = mTabHost.newTabSpec(tag);
spec.setContent(tabContentId);
if(tag.equalsIgnoreCase("Open")){
spec.setIndicator("", getResources().getDrawable(R.drawable.feed));
spec.setContent(tabContentId);
}else if(tag.equalsIgnoreCase("Approved")){
spec.setIndicator("", getResources().getDrawable(R.drawable.trend));
spec.setContent(tabContentId);
}else if(tag.equalsIgnoreCase("Decline")){
spec.setIndicator("", getResources().getDrawable(R.drawable.popularr));
spec.setContent(tabContentId);
}
for(int i=0;i<mTabHost.getTabWidget().getChildCount();i++)
{
mTabHost.getTabWidget().getChildAt(0).setBackgroundColor(Color.parseColor("#fff498"));
}
return spec;
}
public void onTabChanged(String tabId) {
for(int i=0;i<mTabHost.getTabWidget().getChildCount();i++)
{
mTabHost.getTabWidget().getChildAt(i).setBackgroundColor(Color.WHITE);
}
if (TAB_1.equals(tabId)) {
// updateTab(R.id.tab_1);
mCurrentTab = 0;
//Toast.makeText(getApplicationContext(), "1No Guest list for Today", Toast.LENGTH_SHORT).show();
mTabHost.getTabWidget().getChildAt(mTabHost.getCurrentTab()).setBackgroundColor(Color.parseColor("#fff498"));
}
if (TAB_2.equals(tabId)) {
//updateTab(R.id.tab_2);
mCurrentTab = 1;
//Toast.makeText(getApplicationContext(), "2No Guest list for Today", Toast.LENGTH_SHORT).show();
mTabHost.getTabWidget().getChildAt(mTabHost.getCurrentTab()).setBackgroundColor(Color.parseColor("#fff498"));
//http://192.168.21.74/mynetwork/formapi/trending
//http://192.168.21.74/mynetwork/formapi/popular
}
if (TAB_3.equals(tabId)) {
//updateTab(R.id.tab_2);
mCurrentTab = 2;
// Toast.makeText(getApplicationContext(), "3No Guest list for Today", Toast.LENGTH_SHORT).show();
mTabHost.getTabWidget().getChildAt(mTabHost.getCurrentTab()).setBackgroundColor(Color.parseColor("#fff498"));
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
Xml layout:
<?xml version="1.0" encoding="utf-8"?>
<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#android:id/tabhost"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<LinearLayout
android:id="#+id/linearLayout1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<FrameLayout
android:id="#android:id/tabcontent"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1" >
<ListView
android:id="#+id/tab_1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<ListView
android:id="#+id/tab_2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<ListView
android:id="#+id/tab_3"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
</FrameLayout>
<TabWidget
android:id="#android:id/tabs"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="0" >
</TabWidget>
</LinearLayout>
</TabHost>
Put all your list views in PullToRefreshLayout and give R.id.tab_1 R.id.tab_2 R.id.tab_3 id's to your PullToRefreshLayout instead of ListView
<uk.co.senab.actionbarpulltorefresh.library.PullToRefreshLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/tab_1"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:id="#+id/listview1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
</uk.co.senab.actionbarpulltorefresh.library.PullToRefreshLayout>
same for rest of the listview
In java inside onCreate of the activity:
mTabHost = (TabHost) findViewById(android.R.id.tabhost);
mPullToRefreshLayout= (ListView)findViewById(R.id.tab_1);
mPullToRefreshLayout1 = (ListView)findViewById(R.id.tab_2);
mPullToRefreshLayout2 = (ListView)findViewById(R.id.tab_3);
listview = (ListView)findViewById(R.id.listview1);
listview1 = (ListView)findViewById(R.id.listview2);
listview2 = (ListView)findViewById(R.id.listview3);
ActionBarPullToRefresh.from(this)
// Mark All Children as pullable
.allChildrenArePullable()
// Set the OnRefreshListener
.listener(this)
// Finally commit the setup to our PullToRefreshLayout
.setup(mPullToRefreshLayout);
on tab change:
public void onTabChanged(String tabId) {
for(int i=0;i<mTabHost.getTabWidget().getChildCount();i++)
{
mTabHost.getTabWidget().getChildAt(i).setBackgroundColor(Color.WHITE);
}
if (TAB_1.equals(tabId)) {
// updateTab(R.id.tab_1);
mCurrentTab = 0;
//Toast.makeText(getApplicationContext(), "1No Guest list for Today", Toast.LENGTH_SHORT).show();
mTabHost.getTabWidget().getChildAt(mTabHost.getCurrentTab()).setBackgroundColor(Color.parseColor("#fff498"));
ActionBarPullToRefresh.from(this)
// Mark All Children as pullable
.allChildrenArePullable()
// Set the OnRefreshListener
.listener(this)
// Finally commit the setup to our PullToRefreshLayout
.setup(mPullToRefreshLayout);
}
if (TAB_2.equals(tabId)) {
//updateTab(R.id.tab_2);
mCurrentTab = 1;
//Toast.makeText(getApplicationContext(), "2No Guest list for Today", Toast.LENGTH_SHORT).show();
mTabHost.getTabWidget().getChildAt(mTabHost.getCurrentTab()).setBackgroundColor(Color.parseColor("#fff498"));
//http://192.168.21.74/mynetwork/formapi/trending
//http://192.168.21.74/mynetwork/formapi/popular
ActionBarPullToRefresh.from(this)
// Mark All Children as pullable
.allChildrenArePullable()
// Set the OnRefreshListener
.listener(this)
// Finally commit the setup to our PullToRefreshLayout
.setup(mPullToRefreshLayout1);
}
if (TAB_3.equals(tabId)) {
//updateTab(R.id.tab_2);
mCurrentTab = 2;
// Toast.makeText(getApplicationContext(), "3No Guest list for Today", Toast.LENGTH_SHORT).show();
mTabHost.getTabWidget().getChildAt(mTabHost.getCurrentTab()).setBackgroundColor(Color.parseColor("#fff498"));
ActionBarPullToRefresh.from(this)
// Mark All Children as pullable
.allChildrenArePullable()
// Set the OnRefreshListener
.listener(this)
// Finally commit the setup to our PullToRefreshLayout
.setup(mPullToRefreshLayout2);
}
}

Replacing JSON Populated TextView with JSON Populated ListView [duplicate]

This question already has an answer here:
JSON String is incorrectly mapped to textviews
(1 answer)
Closed 9 years ago.
I have a JSON request which returns a response from youtube containing the comments for a particular video. I currently have 3 textviews: one for the name/uploader, one for the content, and one for the date published - which are then populated with the data from my JSON response.
My problem is - only the first comment, date published and uploader appear.
I belive I'll need to replace my textviews with a list view and parse the 3 fields to it - I simply do not know how.
JAVA
public class Player extends YouTubeBaseActivity implements
YouTubePlayer.OnInitializedListener {
public static final String API_KEY = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.player);
String title = getIntent().getStringExtra("title");
String uploader = getIntent().getStringExtra("uploader");
String viewCount = getIntent().getStringExtra("viewCount");
TextView titleTv = (TextView) findViewById(R.id.titleTv);
TextView uploaderTv = (TextView) findViewById(R.id.uploaderTv);
TextView viewCountTv = (TextView) findViewById(R.id.viewCountTv);
titleTv.setText(title);
uploaderTv.setText("by" + uploader + " |");
viewCountTv.setText(viewCount + " views");
YouTubePlayerView youTubePlayerView = (YouTubePlayerView) findViewById(R.id.youtubeplayerview);
youTubePlayerView.initialize(API_KEY, this);
Handler handler = new Handler(new Handler.Callback() {
#Override
public boolean handleMessage(Message msg) {
return false;
}
});
GetYouTubeUserCommentsTask task = new GetYouTubeUserCommentsTask(handler , viewCount);
task.execute();
}
#Override
public void onInitializationFailure(Provider provider,
YouTubeInitializationResult result) {
Toast.makeText(getApplicationContext(), "onInitializationFailure()",
Toast.LENGTH_LONG).show();
}
#Override
public void onInitializationSuccess(Provider provider,
YouTubePlayer player, boolean wasRestored) {
if (!wasRestored) {
String video_id = getIntent().getStringExtra("id");
player.loadVideo(video_id);
}
}
public final class GetYouTubeUserCommentsTask extends
AsyncTask<Void, Void, Void> {
public static final String LIBRARY = "CommentsLibrary";
private final Handler replyTo;
private final String username;
String video_id = getIntent().getStringExtra("id");
public GetYouTubeUserCommentsTask(Handler replyTo, String username) {
this.replyTo = replyTo;
this.username = username;
}
#Override
protected Void doInBackground(Void... arg0) {
try {
HttpClient client = new DefaultHttpClient();
HttpUriRequest request = new HttpGet(
"http://gdata.youtube.com/feeds/api/videos/"
+ video_id
+ "/comments?v=2&alt=json&start-index=1&max-results=50&prettyprint=true");
HttpResponse response = client.execute(request);
String jsonString = StreamUtils.convertToString(response
.getEntity().getContent());
JSONObject json = new JSONObject(jsonString);
JSONArray jsonArray = json.getJSONObject("feed").getJSONArray(
"entry");
List<Comments> comments = new ArrayList<Comments>();
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject entry = jsonArray.getJSONObject(i);
JSONArray authorArray = entry.getJSONArray("author");
JSONObject publishedObject = entry.getJSONObject("published");
String published = publishedObject.getString("$t");
JSONObject contentObject = entry.getJSONObject("content");
String content = contentObject.getString("$t");
JSONObject authorObject = authorArray.getJSONObject(0);
JSONObject nameObject = authorObject.getJSONObject("name");
String name = nameObject.getString("$t");
comments.add(new Comments(name, content, published));
CommentsLibrary lib = new CommentsLibrary(published, content, name);
Bundle data = new Bundle();
data.putSerializable(LIBRARY, lib);
Message msg = Message.obtain();
msg.setData(data);
replyTo.sendMessage(msg);
}
} catch (ClientProtocolException e) {
Log.e("Feck", e);
} catch (IOException e) {
Log.e("Feck", e);
} catch (JSONException e) {
Log.e("Feck", e);
}
return null;
}
#Override
protected void onPostExecute(Void result) {
ListView comments = (ListView) findViewById(R.id.comments);
comments.setFilterText(com.idg.omv.domain.CommentsLibrary.getName());
}
}
}
CommentsLibrary
public class CommentsLibrary implements Serializable{
// The username of the owner of the comment
private static String name;
// The comment
private static String content;
// The date the comment was published
private static String published;
public CommentsLibrary(String name, String content, String published) {
this.name = name;
this.content = content;
this.published = published;
}
/**
* #return the user name
*/
public static String getName() {
return name;
}
/**
* #return the videos
*/
public static String getContent() {
return content;
}
/**
* #return the videos
*/
public static String getPublished() {
return published;
}
}
XML
<TextView
android:id="#+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="left"
android:text="" />
<TextView
android:id="#+id/content"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/name"
android:layout_weight="1"
android:gravity="left"
android:text="" />
<TextView
android:id="#+id/published"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/content"
android:layout_weight="1"
android:gravity="left"
android:text="" />
Continuing my answer from your previous question # JSON String is incorrectly mapped to textviews
First you need a listview in your layout xml
<ListView
android:id="#+id/list"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
Declare list as a instance variable
ArrayList<CommentsLibrary> list = new ArrayList<CommentsLibrary>();
Then
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String name = jsonObject.optString("name","defaultValue");
String content = jsonObject.optString("content","defaultValue");
String published = jsonObject.optString("published","defaultValue");
list.add(new CommentsLibrary(name, content, published));
}
Then initialize listview
ListView lv =(ListView)findViewById(R.id.list);
CustomAdapter cus = new CustomAdapter(ActivityName.this,list);
lv.setAdapter(cus);
Define a custom layout with 3 textviews. (list_item.xml)
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="18dp"
android:layout_marginTop="31dp"
android:text="TextView" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/textView1"
android:layout_alignBottom="#+id/textView1"
android:layout_centerHorizontal="true"
android:text="TextView" />
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/textView2"
android:layout_alignBottom="#+id/textView2"
android:layout_alignParentRight="true"
android:layout_marginRight="24dp"
android:text="TextView" />
</RelativeLayout>
Then define a custom adapter by extending a base adapter. Override getView inflate the custom layout and set text views there.
public class CustomAdapter extends BaseAdapter
{
LayoutInfalter mInflater;
ArrayList<CommentsLibrary> list;
public CustomAdapter(Context context,ArrayList<CommentsLibrary> list)
{
mInflater = LayoutInfalter.from(context);
this.list = list;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return list.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ViewHolder holder;
if(convertView==null)
{
convertView =minflater.inflate(R.layout.list_item, parent,false);
holder = new ViewHolder();
holder.tv1 = (TextView) convertView.findViewById(R.id.textView1);
holder.tv2 = (TextView) convertView.findViewById(R.id.textView2);
holder.tv3 = (TextView) convertView.findViewById(R.id.textView3);
convertView.setTag(holder);
}
else
{
holder= (ViewHolder) convertView.getTag();
}
holder.tv1.setText(list.get(position).getName());
holder.tv2.setText(list.get(position).getContent());
holder.tv3.setText(list.get(position).getPublished());
return convertView;
}
static class ViewHolder
{
TextView tv1,tv2,tv3
}
}
You need to add a list view in your layout and populate it using an ArrayAdapter. Here's a tutorial that shows you how - http://www.vogella.com/articles/AndroidListView/article.html#arrayAdapter

Categories

Resources