Use ListActivity inside a Fragment - java

Here are two codes that I wanted to combine and make it work, I have this navigation drawer which I wanted to put my post comment post inside and enable it to run.
To enable it to run, I will need to make the listActivity runs inside a fragments. It's not possible to extend two activities, so I would like the community to take a look at my code if it can be connect and make it works. This code I got it online.
The HomeFragment.java
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class HomeFragment extends Fragment {
public HomeFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home, container,
false);
return rootView;
}
ReadComments.java
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
public class ReadComments extends ListActivity {
private static final String READ_COMMENTS_URL = "http://www.xxxx.com/webservice/comments.php";
private static final String TAG_MESSAGE = "message";
private static final String TAG_POSTS = "posts";
private static final String TAG_POST_ID = "post_id";
private static final String TAG_SUCCESS = "success";
private static final String TAG_TITLE = "title";
private static final String TAG_USERNAME = "username";
private JSONArray mComments = null;
private ArrayList<HashMap<String, String>> mCommentList;
private ProgressDialog pDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// note that use read_comments.xml instead of our single_post.xml
setContentView(R.layout.fragment_home);
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
// loading the comments via AsyncTask
new LoadComments().execute();
}
public void addComment(View v) {
Intent i = new Intent(ReadComments.this, AddComment.class);
startActivity(i);
}
/**
* Retrieves recent post data from the server.
*/
public void updateJSONdata() {
// Instantiate the arraylist to contain all the JSON data.
// we are going to use a bunch of key-value pairs, referring
// to the json element name, and the content, for example,
// message it the tag, and "I'm awesome" as the content..
mCommentList = new ArrayList<HashMap<String, String>>();
// Bro, it's time to power up the J parser
JSONParser jParser = new JSONParser();
// Feed the beast our comments url, and it spits us
// back a JSON object. Boo-yeah Jerome.
JSONObject json = jParser.getJSONFromUrl(READ_COMMENTS_URL);
// when parsing JSON stuff, we should probably
// try to catch any exceptions:
try {
// I know I said we would check if "Posts were Avail." (success==1)
// before we tried to read the individual posts, but I lied...
// mComments will tell us how many "posts" or comments are
// available
mComments = json.getJSONArray(TAG_POSTS);
// looping through all posts according to the json object returned
for (int i = 0; i < mComments.length(); i++) {
JSONObject c = mComments.getJSONObject(i);
// gets the content of each tag
String title = c.getString(TAG_TITLE);
String content = c.getString(TAG_MESSAGE);
String username = c.getString(TAG_USERNAME);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_TITLE, title);
map.put(TAG_MESSAGE, content);
map.put(TAG_USERNAME, username);
// adding HashList to ArrayList
mCommentList.add(map);
// annndddd, our JSON data is up to date same with our array
// list
}
} catch (JSONException e) {
e.printStackTrace();
}
}
/**
* Inserts the parsed data into the listview.
*/
private void updateList() {
ListAdapter adapter = new SimpleAdapter(this, mCommentList,
R.layout.single_post, new String[] { TAG_TITLE, TAG_MESSAGE,
TAG_USERNAME }, new int[] { R.id.title, R.id.message,
R.id.username });
// I shouldn't have to comment on this one:
setListAdapter(adapter);
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
}
});
}
public class LoadComments extends AsyncTask<Void, Void, Boolean> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(ReadComments.this);
pDialog.setMessage("Loading Comments...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected Boolean doInBackground(Void... arg0) {
updateJSONdata();
return null;
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
pDialog.dismiss();
updateList();
}
}
}

Use a ListFragment for this, you can find the documentation and reference here: http://developer.android.com/reference/android/app/ListFragment.html
you can google examples (e.g: http://www.vogella.com/tutorials/AndroidListView/article.html#listactivity)

Related

SearchView filter in ListView [duplicate]

here is my main activity
package com.javacodegeeks.android.lbs;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;
import lbs.promotion.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;
public class Curve extends Activity {
private ProgressDialog pDialog;
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> DaftarPromotion = new ArrayList<HashMap<String, String>>();
private static String url_daftar_promotion = "http://10.0.2.2/webserver_maaug/promotion/daftar_promotion.php";
String lon = "101.5178";
String lat = "3.0724";
public static final String TAG_SUCCESS = "success";
public static final String TAG_DAFTAR_PROMOTION = "daftar_promotion";
public static final String TAG_ID_PROMO = "PromoID";
public static final String TAG_NAMA_PROMO = "PromoName";
public static final String TAG_LINK_IMAGE_PROMO = "PromoImage";
public static final String TAG_DESC_PROMO= "PromoDesc";
public static final String TAG_CATE_PROMO = "PromoCate";
public static final String TAG_CONT_PROMO = "PromoContact";
public static final String TAG_DATES_PROMO = "PromoDateStart";
public static final String TAG_DATEE_PROMO = "PromoDateEnd";
JSONArray daftar_promotion = null;
ListView list;
PromotionListAdapter adapter;
EditText inputSearch;
private Curve activity;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_curve);
DaftarPromotion = new ArrayList<HashMap<String, String>>();
new Activity().execute();
activity = this;
list = (ListView) findViewById(R.id.list);
inputSearch = (EditText) findViewById(R.id.search_box);
inputSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
// When user changed the Text
Curve.this.adapter.getFilter().filter(cs);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
});
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
HashMap<String, String> map = DaftarPromotion.get(position);
String pna = map.get(TAG_NAMA_PROMO);
String pde = map.get(TAG_DESC_PROMO);
String pca = map.get(TAG_CATE_PROMO);
String pcon = map.get(TAG_CONT_PROMO);
String pds = map.get(TAG_DATES_PROMO);
String pdae = map.get(TAG_DATEE_PROMO);
Toast.makeText(Curve.this, pna +"\n" + pde +"\n" + pca +"\n" + pds +" to " + pdae +"\n" + pcon,Toast.LENGTH_LONG).show();
}
});
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.smenu, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.about:
Toast.makeText(Curve.this,"Mobile Advertising Application Using GPS V1.0",Toast.LENGTH_LONG).show();
return true;
case R.id.search:{
Intent intent = new Intent(Curve.this, Search.class);
intent.putExtra("lon",lon);
intent.putExtra("lat",lat);
startActivity(intent);
//startActivity(new Intent(this, Search.class));
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void SetListViewAdapter(ArrayList<HashMap<String, String>> daftar) {
adapter = new PromotionListAdapter(activity, daftar);
list.setAdapter(adapter);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == 100) {
Intent intent = getIntent();
finish();
startActivity(intent);
}
}
class Activity extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Curve.this);
pDialog.setMessage("Please Wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
protected String doInBackground(String... args) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
JSONObject json = jParser.makeHttpRequest(url_daftar_promotion, "GET",params);
Log.d("All Products: ", json.toString());
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
daftar_promotion = json.getJSONArray(TAG_DAFTAR_PROMOTION);
for (int i = 0; i < daftar_promotion.length();i++){
JSONObject c = daftar_promotion.getJSONObject(i);
String PromoID = c.getString(TAG_ID_PROMO);
String PromoName = c.getString(TAG_NAMA_PROMO);
String pat = "http://10.0.2.2/webserver_maaug/";
String PromoImage = pat + c.getString(TAG_LINK_IMAGE_PROMO);
String PromoDesc = c.getString(TAG_DESC_PROMO);
String PromoCate = c.getString(TAG_CATE_PROMO);
String PromoDateStart = c.getString(TAG_DATES_PROMO);
String PromoDateEnd = c.getString(TAG_DATEE_PROMO);
String PromoContact = c.getString(TAG_CONT_PROMO);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_ID_PROMO, PromoID);
map.put(TAG_NAMA_PROMO, PromoName);
map.put(TAG_LINK_IMAGE_PROMO, PromoImage);
map.put(TAG_DESC_PROMO, PromoDesc);
map.put(TAG_CATE_PROMO, PromoCate);
map.put(TAG_DATES_PROMO, PromoDateStart);
map.put(TAG_DATEE_PROMO, PromoDateEnd);
map.put(TAG_CONT_PROMO, PromoContact);
DaftarPromotion.add(map);
}
} else {
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
pDialog.dismiss();
runOnUiThread(new Runnable() {
public void run() {
SetListViewAdapter(DaftarPromotion);
}
});
}
}
}
and this is my custom adapter, it is a very simple one, without an object class of it's own
package lbs.promotion;
import java.util.ArrayList;
import java.util.HashMap;
import com.javacodegeeks.android.lbs.Curve;
import com.javacodegeeks.android.lbs.R;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ImageView;
import android.widget.TextView;
public class PromotionListAdapter extends BaseAdapter {
private Activity activity;
private ArrayList<HashMap<String, String>> data;
private static LayoutInflater inflater = null;
public ImageLoader imageLoader;
public PromotionListAdapter(Activity a, ArrayList<HashMap<String, String>> d) {
activity = a;
data = d;
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageLoader = new ImageLoader(activity.getApplicationContext());
}
public int getCount() {
return data.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
if (convertView == null)vi = inflater.inflate(R.layout.item_list_promotion, null);
TextView PromoID = (TextView) vi.findViewById(R.id.PromoID);
TextView PromoName = (TextView) vi.findViewById(R.id.PromoName);
TextView PromoImage = (TextView) vi.findViewById(R.id.PromoImage);
TextView PromoDesc = (TextView) vi.findViewById(R.id.PromoDesc);
TextView PromoCate = (TextView) vi.findViewById(R.id.PromoCate);
TextView PromoContact = (TextView) vi.findViewById(R.id.PromoContact);
TextView PromoDateStart = (TextView) vi.findViewById(R.id.PromoDateStart);
TextView PromoDateEnd = (TextView) vi.findViewById(R.id.PromoDateEnd);
ImageView thumb_image = (ImageView) vi.findViewById(R.id.image_promo);
HashMap<String, String> daftar_promotion = new HashMap<String, String>();
daftar_promotion = data.get(position);
PromoID.setText(daftar_promotion.get(Curve.TAG_ID_PROMO));
PromoName.setText(daftar_promotion.get(Curve.TAG_NAMA_PROMO));
PromoImage.setText(daftar_promotion.get(Curve.TAG_LINK_IMAGE_PROMO));
PromoDesc.setText(daftar_promotion.get(Curve.TAG_DESC_PROMO));
PromoCate.setText(daftar_promotion.get(Curve.TAG_CATE_PROMO));
PromoContact.setText(daftar_promotion.get(Curve.TAG_CONT_PROMO));
PromoDateStart.setText(daftar_promotion.get(Curve.TAG_DATES_PROMO));
PromoDateEnd.setText(daftar_promotion.get(Curve.TAG_DATEE_PROMO));
imageLoader.DisplayImage(daftar_promotion.get(Curve.TAG_LINK_IMAGE_PROMO),thumb_image);
return vi;
}
}
here is my layout.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" >
<!-- Editext for Search -->
<EditText android:id="#+id/search_box"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="type to search"
android:inputType="text"
android:maxLines="1"/>
<ListView
android:id="#+id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:divider="#040404"
android:dividerHeight="1dp"
android:listSelector="#drawable/list_selector" />
</LinearLayout>
how do i get the getfilter() function working? or is there any simpler way to implement filtering in my listview? i want to filter based on my PromoName
A Filter has two major components, the performFiltering(CharSequence) method and the publishResults(CharSequence, FilterResults) method. In your PromotionListAdapter, you'll need to implement the Filterable interface then Override the getFilter() method to return a new Filter that has these methods implemented.
The performFiltering(CharSequence) method is where you'll do the bulk of your work. The CharSequence argument is the data which you're filtering on. Here, you'll first want to determine if the list should even be filtered as the base case. Once you've decided to perform the filtering, create a new ArrayList for your filtered dataset (in your case, a new ArrayList>), and loop through your complete set of list items, adding the values that match the filter to your new ArrayList.
The return type for the performFiltering method is FilterResults. FilterResults is a simple object with two variables, int count and Object results. Once performFiltering has created the new ArrayList with the filtered data, create a new FilterResults, setting your new ArrayList as results and the size of that ArrayList as count.
The publishResults(CharSequence, FilterResults) method is called after performFiltering() returns. The CharSequence parameter is the same String you were filtering on. The FilterResults parameter is the return from performFiltering(). In this method, you'll want to set your new ArrayList as the data source for your List and then call notifyDataSetChanged() to update the UI.
In order to implement this, I've had success when my Adapter keeps track of both the original ArrayList of data and a filtered ArrayList of what is currently being shown. Here's some boilerplate code based on your adapter that can help get you started. I've commented above important lines.
public class PromotionListAdapter extends BaseAdapter implements Filterable
{
private Activity activity;
private static LayoutInflater inflater = null;
public ImageLoader imageLoader;
//Two data sources, the original data and filtered data
private ArrayList<HashMap<String, String>> originalData;
private ArrayList<HashMap<String, String>> filteredData;
public PromotionListAdapter(Activity a, ArrayList<HashMap<String, String>> d)
{
activity = a;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageLoader = new ImageLoader(activity.getApplicationContext());
//To start, set both data sources to the incoming data
originalData = d;
filteredData = d;
}
//For this helper method, return based on filteredData
public int getCount()
{
return filteredData.size();
}
//This should return a data object, not an int
public Object getItem(int position)
{
return filteredData.get(position);
}
public long getItemId(int position)
{
return position;
}
//The only change here is that we'll use filteredData.get(position)
//Even better would be to use getItem(position), which uses the helper method (see the getItem() method above)
public View getView(int position, View convertView, ViewGroup parent)
{
View vi = convertView;
if (convertView == null)vi = inflater.inflate(R.layout.item_list_promotion, null);
TextView PromoID = (TextView) vi.findViewById(R.id.PromoID);
TextView PromoName = (TextView) vi.findViewById(R.id.PromoName);
TextView PromoImage = (TextView) vi.findViewById(R.id.PromoImage);
TextView PromoDesc = (TextView) vi.findViewById(R.id.PromoDesc);
TextView PromoCate = (TextView) vi.findViewById(R.id.PromoCate);
TextView PromoContact = (TextView) vi.findViewById(R.id.PromoContact);
TextView PromoDateStart = (TextView) vi.findViewById(R.id.PromoDateStart);
TextView PromoDateEnd = (TextView) vi.findViewById(R.id.PromoDateEnd);
ImageView thumb_image = (ImageView) vi.findViewById(R.id.image_promo);
HashMap<String, String> daftar_promotion = new HashMap<String, String>();
//Get data from filtered Data
//This line can be replaced with:
// daftar_promotion = getItem(position);
daftar_promotion = filteredData.get(position);
PromoID.setText(daftar_promotion.get(Curve.TAG_ID_PROMO));
PromoName.setText(daftar_promotion.get(Curve.TAG_NAMA_PROMO));
PromoImage.setText(daftar_promotion.get(Curve.TAG_LINK_IMAGE_PROMO));
PromoDesc.setText(daftar_promotion.get(Curve.TAG_DESC_PROMO));
PromoCate.setText(daftar_promotion.get(Curve.TAG_CATE_PROMO));
PromoContact.setText(daftar_promotion.get(Curve.TAG_CONT_PROMO));
PromoDateStart.setText(daftar_promotion.get(Curve.TAG_DATES_PROMO));
PromoDateEnd.setText(daftar_promotion.get(Curve.TAG_DATEE_PROMO));
imageLoader.DisplayImage(daftar_promotion.get(Curve.TAG_LINK_IMAGE_PROMO),thumb_image);
return vi;
}
#Override
public Filter getFilter()
{
return new Filter()
{
#Override
protected FilterResults performFiltering(CharSequence charSequence)
{
FilterResults results = new FilterResults();
//If there's nothing to filter on, return the original data for your list
if(charSequence == null || charSequence.length() == 0)
{
results.values = originalData;
results.count = originalData.size();
}
else
{
ArrayList<HashMap<String,String>> filterResultsData = new ArrayList<HashMap<String,String>>();
for(HashMap<String,String> data : originalData)
{
//In this loop, you'll filter through originalData and compare each item to charSequence.
//If you find a match, add it to your new ArrayList
//I'm not sure how you're going to do comparison, so you'll need to fill out this conditional
if(data matches your filter criteria)
{
filterResultsData.add(data);
}
}
results.values = filterResultsData;
results.count = filteredResultsData.size();
}
return results;
}
#Override
protected void publishResults(CharSequence charSequence, FilterResults filterResults)
{
filteredData = (ArrayList<HashMap<String,String>>)filterResults.values;
notifyDataSetChanged();
}
};
}
}
And there you have it! As far as I can tell, you've already implemented the TextWatcher for your inputText EditText set up properly, so adding the getFilter() method and making a few other minor changes to your Adapter should lead you to a solution. I believe you can also create a member variable on your Adapter for your Filter, so you're not creating a new instance of the class each time getFilter() is called, but I copy/pasted this from a previous project of mine and am sure it works this way. Play with it and see what works for you! Hope this helps! And please do comment if you need anything clarified.
you adapter needs to implement Filterable .
for more info about this (and about listView) , watch the video "the world of listView"
here's a sample code:
http://codetheory.in/android-filters/

Load image in listview

I have an application which uses json to get links and texts and now i want to load the image from the downloaded url (by json) in the Listview.
I can load texts in the listview but i can load images!
PLZ help me i have spended 2 days for this and searched,... but no chance! I really need your help! anyone can help me i'll make a great thanks to him in application. PLZZZ help me.
MY CODE :
package rappage.rapfarsi.media.appteam.rapnews;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.ListFragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import rappage.rapfarsi.media.appteam.Articlectivity;
import rappage.rapfarsi.media.appteam.Main;
import rappage.rapfarsi.media.appteam.R;
import rappage.rapfarsi.media.appteam.json.JSONParser;
public class tab2 extends ListFragment {
static final String url_all_products = "http://normaluse.persianrapapp021.ml/article/get_all_products.php";
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> productsList;
// url to get all products list
final String TAG_SUCCESS = "success";
final String TAG_RAPNEWS = "article";
final String TAG_PID = "pid";
final String TAG_TITLE = "title";
final String TAG_PIC = "pic";
final String TAG_WRITER = "writer";
Bitmap bmp;
// JSON Node names
// products JSONArray
JSONArray rapnews = null;
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.tab_2, container, false);
final View rootView = super.onCreateView(inflater, container, savedInstanceState);
// Hashmap for ListView
productsList = new ArrayList<HashMap<String, String>>();
// Loading products in Background Thread
/**
* Background Async Task to Load all product by making HTTP Request
* */
try {
new LoadAllProducts().execute();
}catch (Exception e)
{
final AlertDialog.Builder dlgAlert = new AlertDialog.Builder(getActivity());
dlgAlert.setMessage("لطفا اینترنت خودرا چک کنید! یا ممکن است سرور از دسترس خارج شده باشد ، برای اخبار اپدیت و مشکلات به ویکی رپ مراجعه کنید!");
dlgAlert.setTitle("Connection Error!");
dlgAlert.setNegativeButton("باشه گرفتم", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
startActivity(new Intent(getActivity() , Main.class));
}
});
dlgAlert.create().show();
}
return v;
}
class LoadAllProducts extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
*/
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Loading, Wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All products from url
*/
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);
// Check your log cat for JSON reponse
Log.d("All Products: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
rapnews = json.getJSONArray(TAG_RAPNEWS);
// looping through All Products
for (int i = 0; i < 11; i++) {
JSONObject c = rapnews.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_PID);
String name = c.getString(TAG_TITLE);
String pic = c.getString(TAG_PIC);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_PID, id);
map.put(TAG_TITLE, name);
map.put(TAG_PIC, pic);
// adding HashList to ArrayList
productsList.add(map);
}
} else {
// no products found
// Launch Add New product Activity
Intent i = new Intent(getActivity().getApplicationContext(),
Main.class);
// Closing all previous activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* *
*/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
getActivity().runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
getActivity(), productsList,
R.layout.list_item, new String[]{TAG_PID,
TAG_TITLE},
new int[]{R.id.pid, R.id.txttitle}
);
setListAdapter(adapter);
}
});
}
}
public void onListItemClick(ListView l, View v, int position, long id) {
Toast.makeText(getActivity().getApplicationContext(), "Loading, Please Wait...",
Toast.LENGTH_LONG).show();
String pid = ((TextView) v.findViewById(R.id.pid)).getText()
.toString();
// Starting new intent
Intent in = new Intent(getActivity(),Articlectivity.class);
// sending pid to next activity
in.putExtra(TAG_PID, pid);
// starting new activity and expecting some response back
startActivity(in);
}
}
I WANT TO LOAD IMAGES ATLEAST IN THIS BASE... OR ANYOTHER THING...
There are lots of image loading library available for android.
Have a look at these
https://github.com/square/picasso
https://github.com/nostra13/Android-Universal-Image-Loader
https://code.google.com/p/android-query/wiki/ImageLoading
https://android.googlesource.com/platform/frameworks/volley
https://github.com/koush/UrlImageViewHelper
https://github.com/novoda/image-loader
You can use library by square called Picasso
Here is the documentation.
Picasso.with(context).load("http://i.imgur.com/DvpvklR.png").into(imageView);
Here is a custom adapter for a listview having 2 texts and an image
public class CustomArrayAdapter extends ArrayAdapter<String> {
private final Context context;
private final String[] values1;
private final String[] values2;
public CustomArrayAdapter(Context context, String[] values1, String[] values2) {
super(context, R.layout.some_layout, values1);
this.context = context;
this.values1 = values1;
this.values2 = values2;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
// LayoutInflater inflater = LayoutInflater.from(context);
// View rowView = inflater.inflate(R.layout.some_layout, null);
View rowView = convertView;
if (rowView == null) {
LayoutInflater inflater = LayoutInflater.from(context);
rowView = inflater.inflate(R.layout.some_layout, null);
holder = new ViewHolder();
holder.text1 = (TextView) rowView.findViewById(R.id.firstLine);
holder.text2 = (TextView) rowView.findViewById(R.id.secondLine);
holder.img = (ImageView) rowView.findViewById(R.id.imageView);
rowView.setTag(holder);
}
else {
holder=(ViewHolder)rowView.getTag();
}
holder.text1.setText(values1[position]);
holder.text2.setText(values2[position]);
Picasso.with(rowView.getContext()).load("http://www.9ori.com/store/media/images/8ab579a656.jpg").into(holder.img);
// if (position%2==0) {
// holder.img.setImageResource(R.drawable.correct);
// }
// else {
// holder.img.setImageResource(R.drawable.incorrect);
// }
return rowView;
}
public static class ViewHolder {
public TextView text1, text2;
public ImageView img;
}
}

Android: item list click on JSON generated list view - unable to click

I am getting a JSON from a url to generate a list view of contact names & numbers. I intend to make it where users can just tap on the contact name or phone to make a call directly. But I am having problem to get the tap on the item detected. I tried to put a log on the 'onItemClick' but it seems that it is not being called. Can you help see where I did wrong? Here is my code
package com.example.hk.sample;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
public class AllAccepted extends Activity {
ListView list;
TextView phone;
TextView name;
ArrayList<HashMap<String, String>> oslist = new ArrayList<HashMap<String, String>>();
//URL to get JSON Array
private static String url;
//JSON Node Names
private static final String TAG_OS = "myjson";
private static final String TAG_VER = "phone";
private static final String TAG_NAME = "name";
JSONArray android = null;
//String matchId = Singleton.getInstance().getMatchIdString();
String matchId = "80";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.all_accepted);
list = (ListView) findViewById(R.id.listView1);
url = "http://demo.com/list.php?match_id="+ matchId;
Log.e("final view", "final layout array list");
oslist = new ArrayList<HashMap<String, String>>();
new JSONParse().execute();
final Button btnHistory = (Button) findViewById(R.id.goHome);
btnHistory.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent myIntent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(myIntent);
}
});
}
protected void onItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
Log.e("item clicks", "selected: " + position);
}
private class JSONParse extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
phone = (TextView)findViewById(R.id.listPhone);
name = (TextView)findViewById(R.id.listName);
pDialog = new ProgressDialog(AllAccepted.this);
pDialog.setMessage("Getting Data ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... args) {
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url);
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
pDialog.dismiss();
try {
// Getting JSON Array from URL
android = json.getJSONArray(TAG_OS);
for(int i = 0; i < android.length(); i++){
JSONObject c = android.getJSONObject(i);
// Storing JSON item in a Variable
String ver = c.getString(TAG_VER);
String name = c.getString(TAG_NAME);
// Adding value HashMap key => value
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_VER, ver);
map.put(TAG_NAME, name);
oslist.add(map);
//list=(ListView)findViewById(R.id.listView1);
ListAdapter adapter = new SimpleAdapter(AllAccepted.this, oslist,
R.layout.all_accepted_layout,
new String[] { TAG_VER,TAG_NAME }, new int[] {
R.id.listPhone,R.id.listName});
list.setAdapter(adapter);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
#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;
}
#Override
public void onBackPressed() {
}
}
Thanks in advance.
SOLUTION FOUND:
add this into onCreate method
list = (ListView) findViewById(R.id.listView1);
list.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Log.e("item clicks", "selected: " + position);
String item = list.getItemAtPosition(position).toString();
String contactNum = ((TextView)view.findViewById(R.id.listPhone)).getText().toString();
Log.e("phone number", contactNum);
Intent intent = new Intent(Intent.ACTION_CALL);
intent.setData(Uri.parse("tel:" + contactNum));
startActivity(intent);
}
});
thanks to Kunu for the help
Use this on your onCreate()
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View view, int position,
long id) {
Log.e("item clicks", "selected: " + position);
String contactNum = ((TextView)view.findViewById(R.id.listPhone)).getText().toString();
phoneCall(contactNum);
}
});
and don't forget to import import android.widget.AdapterView.OnItemClickListener;
After retrieving the number try this to make a call
public void phoneCall(String number)
{
String phoneCallUri = "tel:"+number;
Intent phoneCallIntent =new Intent(Intent.ACTION_CALL);
phoneCallIntent.setData(Uri.parse(phoneCallUri));
startActivity(phoneCallIntent);
}
to set the itemClickListener use :
listView.setOnItemClickListener(ActivityName.this);
Override the method, and also inside the xml
set the focusableInTouchMode to false, and also focusable to false for the textviews
Hope that helps
in OnCreate list.setOnItemClickListener(new OnItemClickListener() {});and then Add unimplement method
public class MainActivity extends Activity {
ListView lView ;
String[] ara={"a","b","c","d","e","f"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lView=(ListView)findViewById(R.id.listView1);
ListAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1,ara);
lView.setAdapter(adapter);
lView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
}});
}
}

android switch intent dynamically

I am trying to create a main menu activity in android which dynamically selects the activity destination from its position on the page.
MainMenu.java
package com.verscreative.BowlTrack;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;
import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
public class MainMenu extends SherlockActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_menu);
GridView gridview = (GridView) findViewById(R.id.grid);
gridview.setAdapter(new HomeMenuAdapter());
gridview.setPadding(50, 40, 50, 40);
gridview.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
//Activities That are invoked by the click
String[] mActivitiesIds = {
getString(R.string.menu_launch_0),
getString(R.string.menu_launch_1),
getString(R.string.menu_launch_2),
getString(R.string.menu_launch_3),
getString(R.string.menu_launch_4),
getString(R.string.menu_launch_5)
};
String packageName = "com.verscreative.BowlTrack";
String className = mActivitiesIds[position]+".class";
//TODO: Switch Toast To Activity Intent
Intent i = new Intent();
i.setClassName(packageName, className);
try{
startActivity(i);
}catch(Exception e){
Toast t = Toast.makeText(getApplicationContext(), "Cannot Find Activity", Toast.LENGTH_LONG);
t.show();
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getSupportMenuInflater();
inflater.inflate(R.menu.main_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(com.actionbarsherlock.view.MenuItem item) {
switch (item.getItemId()) {
case R.id.action_settings:
activateSettings();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void activateSettings(){
Intent i = new Intent(this, SettingsActivity.class);
startActivity(i);
}
public class HomeMenuAdapter extends BaseAdapter {
public HomeMenuAdapter() {
}
public int getCount() {
return mThumbIds.length;
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
// create a new ImageView for each item referenced by the Adapter
public View getView(int position, View convertView, ViewGroup parent) {
TextView tv;
if (convertView == null) {
tv = new TextView(getApplicationContext());
tv.setGravity(Gravity.CENTER | Gravity.BOTTOM);
tv.setPadding(0, 10, 0, 10);
} else {
tv = (TextView) convertView;
}
tv.setCompoundDrawablesWithIntrinsicBounds(0, mThumbIds[position], 0, 0);
tv.setText(mTextIds[position]);
tv.setHeight(300);
tv.setTextColor(Color.WHITE);
return tv;
}
// references to our images
private Integer[] mThumbIds = {
android.R.drawable.ic_menu_add,
android.R.drawable.ic_menu_view,
android.R.drawable.ic_menu_info_details,
android.R.drawable.ic_menu_close_clear_cancel,
android.R.drawable.ic_menu_close_clear_cancel,
android.R.drawable.ic_menu_preferences
};
private String[] mTextIds = {
getString(R.string.menu_item_0),
getString(R.string.menu_item_1),
getString(R.string.menu_item_2),
getString(R.string.menu_item_3),
getString(R.string.menu_item_4),
getString(R.string.menu_item_5)
};
}
}
However whatever I do it always says "Cannot Find Activity".
If I change:
String packageName = "com.verscreative.BowlTrack";
String className = mActivitiesIds[position]+".class";
Intent i = new Intent();
i.setClassName(packageName, className);
to for example:
Context packageName = MainMenu.this;
Class<ViewGamesActivity> className = ViewGamesActivity.class;
Intent i = new Intent();
i.setClass(packageName, className);
It works fine, but all options do the same thing!
strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">BowlTrack</string>
<string name="action_settings">Settings</string>
<string name="menu_item_0">Add New Game</string>
<string name="menu_item_1">View Games</string>
<string name="menu_item_2">Stats</string>
<string name="menu_item_3">3-Not</string>
<string name="menu_item_4">4-Not</string>
<string name="menu_item_5">Settings</string>
<string name="menu_launch_0">NewGameActivity</string>
<string name="menu_launch_1">ViewGamesActivity</string>
<string name="menu_launch_2">ViewOverallActivity</string>
<string name="menu_launch_3">3-Not</string>
<string name="menu_launch_4">4-Not</string>
<string name="menu_launch_5">SettingsActivity</string>
<color name="black">#000000</color>
<color name="bwtk">#88078b</color>
<string name="title_activity_view_games">View Games</string>
</resources>
ViewGamesActivity.java
package com.verscreative.BowlTrack;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
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.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
public class ViewGamesActivity extends SherlockActivity {
public class ViewGames extends ListActivity {
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> productsList;
// url to get all products list
private static final String url_all_products = "http://api.androidhive.info/android_connect/get_all_products.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCTS = "products";
private static final String TAG_PID = "pid";
private static final String TAG_NAME = "name";
// products JSONArray
JSONArray products = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_games);
// Hashmap for ListView
productsList = new ArrayList<HashMap<String, String>>();
// Loading products in Background Thread
new LoadAllProducts().execute();
// Get listview
ListView lv = getListView();
// on seleting single product
// launching Edit Product Screen
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String pid = ((TextView) view.findViewById(R.id.pid))
.getText().toString();
// TODO: Starting new intent
// Intent in = new Intent(getApplicationContext(),
// EditProductActivity.class);
// sending pid to next activity
// in.putExtra(TAG_PID, pid);
// starting new activity and expecting some response
// back
// startActivityForResult(in, 100);
}
});
}
// Response from Edit Product Activity
#Override
protected void onActivityResult(int requestCode, int resultCode,
Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// if result code 100
if (resultCode == 100) {
// if result code 100 is received
// means user edited/deleted product
// reload this screen again
Intent intent = getIntent();
finish();
startActivity(intent);
}
}
/**
* Background Async Task to Load all product by making HTTP Request
* */
class LoadAllProducts extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(ViewGamesActivity.this);
pDialog.setMessage("Loading products. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All products from url
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_products,
"GET", params);
// Check your log cat for JSON reponse
Log.d("All Products: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
products = json.getJSONArray(TAG_PRODUCTS);
// looping through All Products
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_PID);
String name = c.getString(TAG_NAME);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key =>
// value
map.put(TAG_PID, id);
map.put(TAG_NAME, name);
// adding HashList to ArrayList
productsList.add(map);
}
} else {
// TODO: no products found
// Launch Add New product Activity
// Intent i = new Intent(getApplicationContext(),
// NewProductActivity.class);
// Closing all previous activities
// i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// startActivity(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
ViewGamesActivity.this, productsList,
R.layout.list_item, new String[] { TAG_PID,
TAG_NAME }, new int[] { R.id.pid,
R.id.name });
// updating listview
setListAdapter(adapter);
}
});
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getSupportMenuInflater();
inflater.inflate(R.menu.main_menu, menu);
return true;
}
}
Thanks to jimpanzer and sherif-elkhatib, I have combined your comments to find the answer.
The Answer is Changing:
String className = mActivitiesIds[position]+".class";
to this:
String className = "com.verscreative.BowlTrack."+mActivitiesIds[position];
I don't think you need to specify the .class
Try this
String className = mActivitiesIds[position];
Otherwise, a more efficient solution would be to have a 2D array as such :
Object[][] mActivitiesIds =
{
{ getString(R.string.menu_launch_0), Activity1.class }
{ getString(R.string.menu_launch_1), Activity1.class }
{ getString(R.string.menu_launch_2), Activity1.class }
{ getString(R.string.menu_launch_3), Activity1.class }
{ getString(R.string.menu_launch_4), Activity1.class }
{ getString(R.string.menu_launch_5) Activity1.class }
};
Then simply use mActivitiesIds[n][1] to get the class...

Android Listview issues in adding data from AsyncTask

I am using android listview with lazyadapter to show images and textview in list.
and when user scrolls to the bottom i am using AsyncTask to add more contents but when i execute AsyncTask it kills the process.
here is my code.
mainactivity
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.NodeList;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.sax.Element;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
public class AndroidJSONParsingActivity extends Activity {
// url to make request
// JSON Node names
static final String TAG_CONTACTS = "comics";
static final String TAG_ID = "id";
static final String TAG_NAME = "title";
static final String TAG_EMAIL = "id";
static final String TAG_PHONE_MOBILE = "image";
// contacts JSONArray
JSONArray contacts = null;
ListView list;
LazyAdapter adapter;
static int counter = 0;
ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
list=(ListView)findViewById(R.id.list);
// call the function
LoadData();
}
public void LoadData(){
String url = "http://myurl?start=" + counter;
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);
try {
// Getting Array of Contacts
contacts = json.getJSONArray(TAG_CONTACTS);
// looping through All Contacts
for(int i = 0; i < contacts.length(); i++){
JSONObject c = contacts.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String email = c.getString(TAG_EMAIL);
String mobile = "http://www.funnydash.com/uploads/s/" + c.getString(TAG_PHONE_MOBILE);
// Phone number is agin JSON Object
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_ID, id);
map.put(TAG_NAME, name);
map.put(TAG_EMAIL, email);
map.put(TAG_PHONE_MOBILE, mobile);
// adding HashList to ArrayList
contactList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
/**
* Updating parsed JSON data into ListView
* */
// Getting adapter by passing xml data ArrayList
adapter=new LazyAdapter(this, contactList);
list.setAdapter(adapter);
list.setOnScrollListener(new EndlessScrollListener());
}
public class BackgroundLoadMore extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
// Showing progress dialog before sending http request
}
protected Void doInBackground(Void... unused) {
LoadData();
return (null);
}
protected void onPostExecute(Void unused) {
// On completing background task
// closing progress dialog etc,.
list.setOnScrollListener(new EndlessScrollListener());
}
}
public class EndlessScrollListener implements OnScrollListener {
private int visibleThreshold = 0;
private int currentPage = 0;
private int previousTotal = 0;
private boolean loading = true;
public EndlessScrollListener() {
}
public EndlessScrollListener(int visibleThreshold) {
this.visibleThreshold = visibleThreshold;
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
if (loading) {
if (totalItemCount > previousTotal) {
loading = false;
previousTotal = totalItemCount;
counter +=12;
}
}
if (!loading && (totalItemCount - visibleItemCount) <= (firstVisibleItem + visibleThreshold)) {
// I load the next page of gigs using a background task,
// but you can call any function here.
new BackgroundLoadMore().execute();
loading = true;
}
}
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
}
}
Lazyadapter.java
import java.util.ArrayList;
import java.util.HashMap;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class LazyAdapter extends BaseAdapter {
private Activity activity;
private ArrayList<HashMap<String, String>> data;
private static LayoutInflater inflater=null;
public ImageLoader imageLoader;
public LazyAdapter(Activity a, ArrayList<HashMap<String, String>> d) {
activity = a;
data=d;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageLoader=new ImageLoader(activity.getApplicationContext());
}
public int getCount() {
return data.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi=convertView;
if(convertView==null)
vi = inflater.inflate(R.layout.list_row, null);
TextView title = (TextView)vi.findViewById(R.id.title); // title
TextView artist = (TextView)vi.findViewById(R.id.artist); // artist name
ImageView thumb_image=(ImageView)vi.findViewById(R.id.list_image); // thumb image
HashMap<String, String> song = new HashMap<String, String>();
song = data.get(position);
// Setting all values in listview
title.setText(song.get(AndroidJSONParsingActivity.TAG_NAME));
artist.setText(song.get(AndroidJSONParsingActivity.TAG_ID));
imageLoader.DisplayImage(song.get(AndroidJSONParsingActivity.TAG_PHONE_MOBILE), thumb_image);
return vi;
}
}
and this is what i get in my logcat
The problem is because you're attempting to set an adapter on your list from outside the UI thread. Views in Android can not be modified in a background thread, which in this case, means you can not modify the UI from the doInBackground method of an AsyncTask. So, your method LoadData() can't call the following:
adapter=new LazyAdapter(this, contactList);
list.setAdapter(adapter);
list.setOnScrollListener(new EndlessScrollListener());
You will need to return some data (probably contactList) from your doInBackground() method, and then move the offending code to the onPostExecute() method, which is run on the UI thread.
The key problem noted in the stack trace is:
CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
1. Always keep the UI thread work on the UI thread, and Non-UI work on the Non-UI thread, this became a law from the arrival of the Honey Comb version of Android.
2. From your above logcat, it points to only one thing, that you are trying to do something from the Non-UI thread on the UI thread (The main Dedicated UI thread).
Here it is.... You are calling it on the doInBackground() which is a Non-UI thread.
adapter=new LazyAdapter(this, contactList);
list.setAdapter(adapter);
list.setOnScrollListener(new EndlessScrollListener());
3. Modify the adapter form UI thread, you can do it in onPostExecute()
You are trying to create a view off the main thread class.
As said on this line
07-26 22:26:36.933: E/AndroidRuntime(16353): Caused by:
android.view.ViewRootImpl$CalledFromWrongThreadException: Only the
original thread that created a view hierarchy can touch its views.
Your main problem is here in your asyncTask. You can not create view items that are not in the original thread. What you can do. is to place this lines on your post method not in do background method or outside asynctask class.
// Getting adapter by passing xml data ArrayList
adapter=new LazyAdapter(this, contactList);
list.setAdapter(adapter);

Categories

Resources