Json image cant load - android

i am getting "text" form json, but i can't get "images".
public class JsonSampleActivity extends ListActivity {
private Context context;
// url to make request
private static String url = "http://www.bounty4u.com/android/sample_json.txt";
//JSON Node names
private static final String TAG_TITLE = "name";
private static final String TAG_IMAGE = "url";
// contacts JSONArray
ArrayList<HashMap<String, String>> jsonlist = new ArrayList<HashMap<String, String>>();
ListView lv ;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
new ProgressTask(JsonSampleActivity.this).execute();
}
private class ProgressTask extends AsyncTask<String, Void, Boolean> {
private ListActivity activity;
public ProgressTask(ListActivity activity) {
this.activity = activity;
context = activity;
}
/** progress dialog to show user that the backup is processing. */
/** application context. */
private Context context;
protected void onPreExecute() {
}
#Override
protected void onPostExecute(final Boolean success) {
ListAdapter adapter = new SimpleAdapter(context, jsonlist,
R.layout.list_item, new String[] { TAG_TITLE, TAG_IMAGE },
new int[] { R.id.title, R.id.image1 });
setListAdapter(adapter);
}
protected Boolean doInBackground(final String... args) {
JsonParser jParser = new JsonParser();
// getting JSON string from URL
JSONArray json = jParser.getJSONFromUrl(url);
for (int i = 0; i < json.length(); i++) {
try {
JSONObject c = json.getJSONObject(i);
String vfuel = c.getString(TAG_TITLE);
String vimage = c.getString(TAG_IMAGE);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_TITLE, vfuel);
map.put(TAG_IMAGE,vimage);
jsonlist.add(map);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return null;
}
}
I am getting an error : resolveUri failed on bad bitmap uri: http://www.bounty4u.com/android/images/angie.jpg
so tell me what is problem?

Related

How to Show JSON DATA in LISTVIEW

I have a JSON data from YouTube. I want to show data in LIST VIEW. But when i run my code I get a blank page. But I have the respond of YouTube DATA API. How can I solve it?
public class MainActivity extends ListActivity {
private ProgressDialog pDialog;
// URL to get contacts JSON
private static String url = "https://www.googleapis.com/youtube/v3/search?part=snippet&maxResult=30&q=natok+bangla+mosharrof+karim&key=AIzaSyCR40QlsuX0aFfBV-wEPDsH_jxna1tDFRA";
private static final String TAG_ITEMS = "items";
private static final String TAG_ID = "id";
private static final String TAG_ID_VIDEOID = "vid";
private static final String TAG_TITLE = "title";
private static final String TAG_DESCRIPTION = "description";
private static final String YouTubeThumbnail = "https://i.ytimg.com/vi/hlaX2OZ_kDg/default.jpg";
private static final String TAG_CHANNELTITLE = "channelTitle";
JSONArray items = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> dataList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dataList = new ArrayList<HashMap<String, String>>();
ListView lv = getListView();
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String vid = ((TextView) view.findViewById(R.id.name))
.getText().toString();
String title = ((TextView) view.findViewById(R.id.email))
.getText().toString();
String description = ((TextView) view.findViewById(R.id.mobile))
.getText().toString();
// Starting single contact activity
Intent in = new Intent(getApplicationContext(),
SingleContactActivity.class);
in.putExtra(TAG_ID_VIDEOID, vid);
in.putExtra(TAG_TITLE, title);
in.putExtra(TAG_DESCRIPTION, description);
startActivity(in);
}
});
new GetContacts().execute();
}
private class GetContacts extends AsyncTask<Void, Void, Boolean> {
#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 Boolean doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
ArrayList<HashMap<String, String>> dataList = new ArrayList<HashMap<String,String>>();
int count = 0;
try {
JSONObject js = new JSONObject(jsonStr);
JSONArray jsItem = js.getJSONArray("items");
for (int i = 0; i < jsItem.length(); i++) {
JSONObject item = jsItem.getJSONObject(i);
JSONObject vid =item.getJSONObject("id");
String videoId = getStringResult(vid.toString(), "videoId");
if (!videoId.equalsIgnoreCase(""))
{
JSONObject snippet =item.getJSONObject("snippet");
String title = sh.getStringResult(snippet.toString(), "title");
HashMap<String, String> map = new HashMap<String, String>();
map.put("name", title);
map.put("vid", videoId);
map.put ("img","http://img.youtube.com/vi/" + videoId + "/hqdefault.jpg");
map.put ("id",++count+"");
dataList.add(map);
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return true;
}
#Override
protected void onPostExecute(Boolean 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, dataList,R.layout.list_item, new String[] { TAG_TITLE, TAG_DESCRIPTION,
TAG_CHANNELTITLE }, new int[] { R.id.name,
R.id.email, R.id.mobile });
setListAdapter(adapter);
}
}
public String getStringResult(String data, String node) {
try {
JSONObject js = new JSONObject(data);
return js.getString(node);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "";
}
}
Use notifyDataSetChanged(). This notifies a change in data and updated the list view. LINK
Here are the changes that would help:
public class MainActivity extends ListActivity {
...
ListAdapter adapter = null;
#Override
public void onCreate(Bundle savedInstanceState) {
...
ListView lv = getListView();
adapter = new SimpleAdapter(
MainActivity.this, dataList,R.layout.list_item, new String[] { TAG_TITLE, TAG_DESCRIPTION,
TAG_CHANNELTITLE }, new int[] { R.id.name,
R.id.email, R.id.mobile });
lv.setListAdapter(adapter);
...
}
private class GetContacts extends AsyncTask<Void, Void, Boolean> {
#Override
protected void onPreExecute() {
...
}
#Override
protected Boolean doInBackground(Void... arg0) {
...
}
#Override
protected void onPostExecute(Boolean result) {
if(adapter ! = null) {
adapter.notifyDataSetChanged();
}
}
public String getStringResult(String data, String node) {
...
}
Explanation:
ListAdapter is the bridge between a ListView and the data that backs the list.
Whenever the data is changed, adapter is responsible to notify about the changed data and consequently the view gets updated with the new data. This is achieved by notifyDataSetChanged().
For some more details, please go through this link.

android from activity to fragment

I'm new to android. I want to put one of the activity under one of the tab of my app(the tab is fragment) when i paste my code into fragment, there's a lot of error...
There's error in new JSONParse().execute(); It shows that the type JSONParse is not visible.
in this line private class JSONParse extends AsyncTask there's error
showing illegal modifier for the class JSONParse.only public, abstract and final are permitted.
this line pDialog = new ProgressDialog(TabActivityQueue.this); it shows the constructor progressDialog is undefined.
All the variables phonenumber, peoplenumber , remarks, status, table2, url are not resolved as variables.
What should I change? I'm really stuck.
Here's the activity code :
public class MainActivity extends Activity {
ListView list;
TextView number;
TextView info;
TextView remark;
TextView statuss;
Button Btngetdata;
ArrayList<HashMap<String, String>> oslist = new ArrayList<HashMap<String, String>>();
//URL to get JSON Array
private static String url = "http://172.22.85.235:8080/Qproject/servlet/Qaction?action_flag=find";
//JSON Node Names
private static final String Table2 = "table2";
private static final String phonenumber = "phonenumber";
private static final String peoplenumber = "peoplenumber";
private static final String remarks = "remarks";
private static final String status = "status";
JSONArray table2 = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
oslist = new ArrayList<HashMap<String, String>>();
Btngetdata = (Button)findViewById(R.id.getdata);
Btngetdata.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new JSONParse().execute();
}
});
}
private class JSONParse extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
number = (TextView)findViewById(R.id.number);
info = (TextView)findViewById(R.id.info);
remark = (TextView)findViewById(R.id.remark);
statuss = (TextView)findViewById(R.id.statuss);
pDialog = new ProgressDialog(MainActivity.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
table2 = json.getJSONArray(Table2);
for(int i = 0; i < table2.length(); i++){
JSONObject c = table2.getJSONObject(i);
// Storing JSON item in a Variable
String number = c.getString(phonenumber);
String info = c.getString(peoplenumber);
String remark = c.getString(remarks);
String statuss = c.getString(status);
// Adding value HashMap key => value
HashMap<String, String> map = new HashMap<String, String>();
map.put(phonenumber, number);
map.put(peoplenumber, info);
map.put(remarks, remark);
map.put(status, statuss);
oslist.add(map);
list=(ListView)findViewById(R.id.list);
ListAdapter adapter = new SimpleAdapter(MainActivity.this, oslist,
R.layout.list_item,
new String[] { phonenumber,peoplenumber, remarks,status }, new int[] {
R.id.number,R.id.info, R.id.remark,R.id.statuss});
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(MainActivity.this, "You Clicked at "+oslist.get(+position).get("name"), Toast.LENGTH_SHORT).show();
}
});
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Here's the fragment where i pasted the activity code in :
public class TabActivityQueue extends Fragment {
ListView list;
TextView number;
TextView info;
TextView remark;
TextView statuss;
Button Btngetdata;
ArrayList<HashMap<String, String>> oslist = new ArrayList<HashMap<String, String>>();
//URL to get JSON Array
public static String url = "http://172.22.85.235:8080/Qproject/servlet/Qaction?action_flag=find";
//JSON Node Names
public static final String Table2 = "table2";
public static final String phonenumber = "phonenumber";
public static final String peoplenumber = "peoplenumber";
public static final String remarks = "remarks";
public static final String status = "status";
JSONArray table2 = null;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
//This layout contains your list view
View view = inflater.inflate(R.layout.activity_tab_activity_queue, container, false);
oslist = new ArrayList<HashMap<String, String>>();
number = (TextView)view.findViewById(R.id.number);
info = (TextView)view.findViewById(R.id.info);
remark = (TextView)view.findViewById(R.id.remark);
statuss = (TextView)view.findViewById(R.id.statuss);
Btngetdata = (Button)view.findViewById(R.id.getdata);
Btngetdata.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new JSONParse().execute();
}
});
return view;
}
}
private class JSONParse extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(TabActivityQueue.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
table2 = json.getJSONArray(Table2);
for(int i = 0; i < table2.length(); i++){
JSONObject c = table2.getJSONObject(i);
// Storing JSON item in a Variable
String number = c.getString(phonenumber);
String info = c.getString(peoplenumber);
String remark = c.getString(remarks);
String statuss = c.getString(status);
// Adding value HashMap key => value
HashMap<String, String> map = new HashMap<String, String>();
map.put(phonenumber, number);
map.put(peoplenumber, info);
map.put(remarks, remark);
map.put(status, statuss);
oslist.add(map);
list=(ListView)findViewById(R.id.list);
ListAdapter adapter = new SimpleAdapter(MainActivity.this, oslist,
R.layout.list_item,
new String[] { phonenumber,peoplenumber, remarks,status }, new int[] {
R.id.number,R.id.info, R.id.remark,R.id.statuss});
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(MainActivity.this, "You Clicked at "+oslist.get(+position).get("name"), Toast.LENGTH_SHORT).show();
}
});
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
public class TabActivityQueue extends Fragment {
ListView list;
TextView number;
TextView info;
TextView remark;
TextView statuss;
Button Btngetdata;
ArrayList<HashMap<String, String>> oslist = new ArrayList<HashMap<String, String>>();
// URL to get JSON Array
public static String url = "http://172.22.85.235:8080/Qproject/servlet/Qaction?action_flag=find";
// JSON Node Names
public static final String Table2 = "table2";
public static final String phonenumber = "phonenumber";
public static final String peoplenumber = "peoplenumber";
public static final String remarks = "remarks";
public static final String status = "status";
JSONArray table2 = null;
private Activity activity;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
// This layout contains your list view
View view = inflater.inflate(R.layout.activity_tab_activity_queue, container, false);
oslist = new ArrayList<HashMap<String, String>>();
number = (TextView) view.findViewById(R.id.number);
info = (TextView) view.findViewById(R.id.info);
remark = (TextView) view.findViewById(R.id.remark);
statuss = (TextView) view.findViewById(R.id.statuss);
Btngetdata = (Button) view.findViewById(R.id.getdata);
Btngetdata.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new JSONParse().execute();
}
});
activity = this.getActivity();
return view;
}
private class JSONParse extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(activity);
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
table2 = json.getJSONArray(Table2);
for (int i = 0; i < table2.length(); i++) {
JSONObject c = table2.getJSONObject(i);
// Storing JSON item in a Variable
String number = c.getString(phonenumber);
String info = c.getString(peoplenumber);
String remark = c.getString(remarks);
String statuss = c.getString(status);
// Adding value HashMap key => value
HashMap<String, String> map = new HashMap<String, String>();
map.put(phonenumber, number);
map.put(peoplenumber, info);
map.put(remarks, remark);
map.put(status, statuss);
oslist.add(map);
list = (ListView) findViewById(R.id.list);
ListAdapter adapter = new SimpleAdapter(activity, oslist, R.layout.list_item, new String[] {phonenumber, peoplenumber, remarks, status}, new int[] {R.id.number, R.id.info,
R.id.remark, R.id.statuss});
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(activity, "You Clicked at " + oslist.get(+position).get("name"), Toast.LENGTH_SHORT).show();
}
});
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
Whereever you have used context as TabActivityQueue.this (or getApplicationCOntext()) change to getActivity() .
Also if some android pre defined method doesn't work try prefix getActivity() like:- getActivity().method();
declare private Activity activity as public Activity activity;

put function to display the loading process

I want to display the loading process when moving activity
This is my java file, where I have to put the function to process my application loading while loading data
public class tehni extends ListActivity {
TextView txt1;
private static String link_url = "http://192.168.32.1/pln/android/berita/tehnik1.php?kode=";
private static final String AR_ID = "id";
private static final String AR_JUDUL = "judul";
private static final String AR_CONTENT = "content";
JSONArray artikel = null;
ArrayList<HashMap<String, String>> daftar_artikel = new ArrayList<HashMap<String, String>>();
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tehni);
JSONParserberita jParser = new JSONParserberita();
JSONObject json = jParser.AmbilJson(link_url + user_name);
try {
artikel = json.getJSONArray("artikel");
for (int i = 0; i < artikel.length(); i++) {
JSONObject ar = artikel.getJSONObject(i);
String id = ar.getString(AR_ID);
String judul = "ID LAPORAN =" + ar.getString(AR_JUDUL);
String content = "STATUS="
+ ar.getString(AR_CONTENT).substring(0, 6);
HashMap<String, String> map = new HashMap<String, String>();
map.put(AR_ID, id);
map.put(AR_JUDUL, judul);
map.put(AR_CONTENT, content);
daftar_artikel.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
this.adapter_listview();
}
}
AsyncTask is an abstract class provided by Android which helps us to use the UI thread properly. This class allows us to perform long/background operations and show its result on the UI thread without having to manipulate threads.
Try to use AsynchTask
public class tehni extends ListActivity {
TextView txt1;
private static String link_url = "http://192.168.32.1/pln/android/berita/tehnik1.php?kode=";
private static final String AR_ID = "id";
private static final String AR_JUDUL = "judul";
private static final String AR_CONTENT = "content";
JSONArray artikel = null;
ArrayList<HashMap<String, String>> daftar_artikel = new ArrayList<HashMap<String, String>>();
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tehni);
new task ().execute();
}
class task extends AsyncTask<String, Integer, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDlg.setMessage("Loading...");
pDlg.setCancelable(false);
pDlg.setTitle(getResources().getString(R.string.app_name));
pDlg.setCancelable(false);
pDlg.show();
}
#Override
protected String doInBackground(String... params) {
JSONParserberita jParser = new JSONParserberita();
JSONObject json = jParser.AmbilJson(link_url + user_name);
try {
artikel = json.getJSONArray("artikel");
for (int i = 0; i < artikel.length(); i++) {
JSONObject ar = artikel.getJSONObject(i);
String id = ar.getString(AR_ID);
String judul = "ID LAPORAN =" + ar.getString(AR_JUDUL);
String content = "STATUS="
+ ar.getString(AR_CONTENT).substring(0, 6);
HashMap<String, String> map = new HashMap<String, String>();
map.put(AR_ID, id);
map.put(AR_JUDUL, judul);
map.put(AR_CONTENT, content);
daftar_artikel.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
pDlg.dismiss();
this.adapter_listview();
}
}
Try to use AsyncTask for web service calls. Refer it fore more details developer.android.com/reference/android/os/AsyncTask.html
public class tehni extends ListActivity {
TextView txt1;
private static String link_url = "http://192.168.32.1/pln/android/berita/tehnik1.php?kode=";
private static final String AR_ID = "id";
private static final String AR_JUDUL = "judul";
private static final String AR_CONTENT = "content";
JSONArray artikel = null;
ArrayList<HashMap<String, String>> daftar_artikel = new ArrayList<HashMap<String, String>>();
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tehni);
new ServiceCallTask().execute();
this.adapter_listview();
}
class ServiceCallTask extends AsyncTask<String, String, String>
{
private ProgressDialog progressDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog=new ProgressDialog(tehni.this, android.R.style.Theme_Translucent_NoTitleBar);
progressDialog.setMessage("Loading...");
progressDialog.show();
}
#Override
protected String doInBackground(String... params) {
try {
JSONParserberita jParser = new JSONParserberita();
JSONObject json = jParser.AmbilJson(link_url + user_name);
artikel = json.getJSONArray("artikel");
for (int i = 0; i < artikel.length(); i++) {
JSONObject ar = artikel.getJSONObject(i);
String id = ar.getString(AR_ID);
String judul = "ID LAPORAN =" + ar.getString(AR_JUDUL);
String content = "STATUS="
+ ar.getString(AR_CONTENT).substring(0, 6);
HashMap<String, String> map = new HashMap<String, String>();
map.put(AR_ID, id);
map.put(AR_JUDUL, judul);
map.put(AR_CONTENT, content);
daftar_artikel.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if(progressDialog!=null)
progressDialog.dismiss();
this.adapter_listview();
}
}
}
Given that you will receive a NetworkOnMainTheadException if running a HTTP request on the UI thread, I will assume that your request is within jParser.AmbilJson().
So, the best approach is to use the methods of AsyncTask like onPreExecute and onPostExecute to display the result in a ProgressBar.

Can't get the string value in Hash Map on List view adapter in Android

I already getting the string value from JSON but it seems to have the problem in Hash map or something, im getting null value on my List adapter. Can anyone help me or tell me if i did something wrong in my code. Thanks in advance.
Here is my code.
The Activity -
public class TestJSON extends Activity{
public static ListView lv;
public static ProgressDialog pDialog;
public static LazyAdapter adapter;
static final String KEY_ITEMS = "items";
static final String KEY_TITLE = "title";
static final String KEY_ID = "id";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.test_json_view);
new AsyncInitial().execute();
// Showing progress dialog before sending http request
pDialog = new ProgressDialog(this);
pDialog.setMessage("Please wait..");
pDialog.setIndeterminate(true);
pDialog.setCancelable(false);
pDialog.show();
lv = (ListView)findViewById(R.id.list);
//lv.setAdapter(new ArrayAdapter(getApplicationContext(), android.R.layout.simple_expandable_list_item_1, items));
}
private class AsyncInitial extends AsyncTask<Void, Void, ArrayList<HashMap<String, String>>> {
ArrayList<HashMap<String, String>> menuItems;
#Override
protected void onPreExecute() {
}
#Override
protected ArrayList<HashMap<String, String>> doInBackground(Void... arg0) {
menuItems = new ArrayList<HashMap<String, String>>();
try {
//if (vid_num <= 0) {
// Get a httpclient to talk to the internet
HttpClient client = new DefaultHttpClient();
// Perform a GET request to YouTube for a JSON list of all the videos by a specific user
//https://gdata.youtube.com/feeds/api/videos?author="+username+"&v=2&alt=jsonc
HttpUriRequest request = new HttpGet("http://gdata.youtube.com/feeds/api/playlists/SP86E04995E07F6BA8?v=2&start-index=1&max-results=50&alt=jsonc");
// Get the response that YouTube sends back
HttpResponse response = client.execute(request);
// Convert this response into a readable string
String jsonString = StreamUtils.convertToString(response.getEntity().getContent());
// Create a JSON object that we can use from the String
JSONObject json = new JSONObject(jsonString);
// For further information about the syntax of this request and JSON-C
// see the documentation on YouTube http://code.google.com/apis/youtube/2.0/developers_guide_jsonc.html
// Get are search result items
JSONArray jsonArray = json.getJSONObject("data").getJSONArray(KEY_ITEMS);
// Get the total number of video
//String vid_num = json.getJSONObject("data").getString("totalItems");
//System.out.println("vid_num-------->"+ vid_num);
// Loop round our JSON list of videos creating Video objects to use within our app
for (int i = 0; i < jsonArray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject jsonObject = jsonArray.getJSONObject(i);
// The title of the video
String title = jsonObject.getJSONObject("video").getString(KEY_TITLE);
System.out.println("Title-------->"+ title);
// A url to the thumbnail image of the video
// We will use this later to get an image using a Custom ImageView
//String TAG_thumbUrl = jsonObject.getJSONObject("video").getJSONObject("thumbnail").getString("sqDefault");
//System.out.println("thumbUrl-------->"+ thumbUrl);
String id = jsonObject.getJSONObject("video").getString(KEY_ID);
System.out.println("video_id-------->"+ id);
map.put(title, KEY_TITLE);
map.put(id, KEY_ID);
menuItems.add(map);
}
} catch (ClientProtocolException e) {
//Log.e("Feck", e);
} catch (IOException e) {
//Log.e("Feck", e);
} catch (JSONException e) {
//Log.e("Feck", e);
}
return menuItems;
}
#Override
protected void onPostExecute(ArrayList<HashMap<String, String>> result) {
super.onPostExecute(result);
adapter = new LazyAdapter(TestJSON.this,menuItems);
lv.setAdapter(adapter);
pDialog.dismiss();
}
}
}
And The adapter
public class LazyAdapter extends BaseAdapter {
private Activity activity;
private static LayoutInflater inflater;
private ArrayList<HashMap<String, String>> data;
public LazyAdapter(TestJSON testJSON, ArrayList<HashMap<String, String>> menuItems) {
activity = testJSON;
data = menuItems;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return data.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
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);
TextView id = (TextView)vi.findViewById(R.id.artist);
HashMap<String, String> item = new HashMap<String, String>();
item = data.get(position);
title.setText(item.get(TestJSON.KEY_TITLE));
id.setText(item.get(TestJSON.KEY_ID));
return vi;
}
}

Main thread freezes when fetching data from URL on Async Task

I am fetching JSON from URL using AsycTask, parsing it and displaying the data onto the listView. I also click the refresh button to once again fetch the JSON from URL for some updating. When i click the refresh button the following takes place;
1) adapter.clear() : clearing the listView's adapter to populate the new data.
2) Fetch JSON from url, parse and display the newly fetched data onto the listView.
3) Meanwhile when fetching the data, I show a progress dialog.
But when i click on the refresh button, the main UI thread freezes during the execution of AsynTask. I mean the refresh button looks pressed until the AsynTask finishes the job as shown below.
Here is my code:
public class AndroidJSONParsingActivity extends SherlockActivity {
// JSON Node names
ArrayList<HashMap<String, String>> placeList = new ArrayList<HashMap<String, String>>();
private static final String TAG_PLACES = "places";
private static final String TAG_PLACE_NAME = "name";
private static final String TAG_PLACE_CATEGORY = "category";
private static final String TAG_PLACE_DISTANCE = "distance";
private static final String TAG_TRAVEL_TIME = "travel_time";
ListAdapter adapter;
public static Context con;
JSONArray places = null;
ListView list;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
con = this;
list = (ListView) findViewById(R.id.listView1);
parseJSON();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getSupportMenuInflater();
inflater.inflate(R.menu.activity_main, menu);
MenuItem menu_item1 = menu.findItem(R.id.menu_item1);
menu_item1.setOnMenuItemClickListener(new OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
Toast.makeText(getApplicationContext(), "refresh",
Toast.LENGTH_LONG).show();
placeList.clear();
parseJSON();
return false;
}
});
return true;
}
public void parseJSON() {
try {
placeList = new JSONParsingTask().execute().get();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
adapter = new SimpleAdapter(this, placeList, R.layout.list_item,
new String[] { TAG_PLACE_NAME, TAG_PLACE_CATEGORY,
TAG_PLACE_DISTANCE, TAG_TRAVEL_TIME }, new int[] {
R.id.name, R.id.category, R.id.distance,
R.id.travel_time });
list.setAdapter(adapter);
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String name = ((TextView) view.findViewById(R.id.name))
.getText().toString();
String category = ((TextView) view.findViewById(R.id.category))
.getText().toString();
String distance = ((TextView) view.findViewById(R.id.distance))
.getText().toString();
String travel_time = ((TextView) view
.findViewById(R.id.travel_time)).getText().toString();
Intent in = new Intent(getApplicationContext(),
SingleMenuItemActivity.class);
in.putExtra(TAG_PLACE_NAME, name);
in.putExtra(TAG_PLACE_CATEGORY, category);
in.putExtra(TAG_PLACE_DISTANCE, distance);
in.putExtra(TAG_TRAVEL_TIME, travel_time);
startActivity(in);
}
});
}
}
class JSONParsingTask extends
AsyncTask<Void, Void, ArrayList<HashMap<String, String>>> {
public Boolean flag = false;
private static String url = "http://some - url";
// JSON Node names
private static final String TAG_PLACES = "places";
private static final String TAG_PLACE_NAME = "name";
private static final String TAG_PLACE_CATEGORY = "category";
private static final String TAG_PLACE_DISTANCE = "distance";
private static final String TAG_TRAVEL_TIME = "travel_time";
ListAdapter adapter;
JSONParser jParser;
ListView list;
static ArrayList<HashMap<String, String>> placeList = new ArrayList<HashMap<String, String>>();
JSONArray places = null;
ProgressDialog JSONParsingDialog = new ProgressDialog(
AndroidJSONParsingActivity.con);
#Override
protected void onPreExecute() {
JSONParsingDialog.setMessage("Preparing data...");
JSONParsingDialog.setCanceledOnTouchOutside(false);
JSONParsingDialog.setCancelable(false);
JSONParsingDialog.show();
}
#Override
protected ArrayList<HashMap<String, String>> doInBackground(Void... params) {
JSONParser jParser = new JSONParser();
final JSONObject json = jParser.getJSONFromUrl(url);
try {
places = json.getJSONArray(TAG_PLACES);
for (int i = 0; i < places.length(); i++) {
JSONObject c = places.getJSONObject(i);
String name = c.getString(TAG_PLACE_NAME);
String category = c.getString(TAG_PLACE_CATEGORY);
String distance = c.getString(TAG_PLACE_DISTANCE);
String travel_time = c.getString(TAG_TRAVEL_TIME);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_PLACE_NAME, name);
map.put(TAG_PLACE_CATEGORY, category);
map.put(TAG_PLACE_DISTANCE, distance);
map.put(TAG_TRAVEL_TIME, travel_time);
placeList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
return placeList;
}
#Override
protected void onPostExecute(ArrayList<HashMap<String, String>> result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
JSONParsingDialog.dismiss();
}
}
All i need is, when i click on the refresh button, it should be smooth and should not freeze until the AsynTask is completed. Any idea how can i do this?
use
new JSONParsingTask().execute();
.get() blocks the caller thread.
more info: Looking for good example of using get() with an AsyncTask in android
Try it like this:
public class AndroidJSONParsingActivity extends SherlockActivity {
// JSON Node names
ArrayList<HashMap<String, String>> placeList = new ArrayList<HashMap<String, String>>();
private static final String TAG_PLACES = "places";
private static final String TAG_PLACE_NAME = "name";
private static final String TAG_PLACE_CATEGORY = "category";
private static final String TAG_PLACE_DISTANCE = "distance";
private static final String TAG_TRAVEL_TIME = "travel_time";
ListAdapter adapter;
public static Context con;
JSONArray places = null;
ListView list;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
con = this;
list = (ListView) findViewById(R.id.listView1);
fetchJSON();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getSupportMenuInflater();
inflater.inflate(R.menu.activity_main, menu);
MenuItem menu_item1 = menu.findItem(R.id.menu_item1);
menu_item1.setOnMenuItemClickListener(new OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
Toast.makeText(getApplicationContext(), "refresh",
Toast.LENGTH_LONG).show();
placeList.clear();
parseJSON();
return false;
}
});
return true;
}
public void fecthJson(){
new JSONParsingTask().execute();
}
public void parseJSON(ArrayList<Hashmap<String, String>> dataList) {
adapter = new SimpleAdapter(this, dataList, R.layout.list_item,
new String[] { TAG_PLACE_NAME, TAG_PLACE_CATEGORY,
TAG_PLACE_DISTANCE, TAG_TRAVEL_TIME }, new int[] {
R.id.name, R.id.category, R.id.distance,
R.id.travel_time });
list.setAdapter(adapter);
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String name = ((TextView) view.findViewById(R.id.name))
.getText().toString();
String category = ((TextView) view.findViewById(R.id.category))
.getText().toString();
String distance = ((TextView) view.findViewById(R.id.distance))
.getText().toString();
String travel_time = ((TextView) view
.findViewById(R.id.travel_time)).getText().toString();
Intent in = new Intent(getApplicationContext(),
SingleMenuItemActivity.class);
in.putExtra(TAG_PLACE_NAME, name);
in.putExtra(TAG_PLACE_CATEGORY, category);
in.putExtra(TAG_PLACE_DISTANCE, distance);
in.putExtra(TAG_TRAVEL_TIME, travel_time);
startActivity(in);
}
});
}
}
class JSONParsingTask extends
AsyncTask<Void, Void, ArrayList<HashMap<String, String>>> {
public Boolean flag = false;
private static String url = "http://some - url";
// JSON Node names
private static final String TAG_PLACES = "places";
private static final String TAG_PLACE_NAME = "name";
private static final String TAG_PLACE_CATEGORY = "category";
private static final String TAG_PLACE_DISTANCE = "distance";
private static final String TAG_TRAVEL_TIME = "travel_time";
ListAdapter adapter;
JSONParser jParser;
ListView list;
static ArrayList<HashMap<String, String>> placeList = new ArrayList<HashMap<String, String>>();
JSONArray places = null;
ProgressDialog JSONParsingDialog = new ProgressDialog(
AndroidJSONParsingActivity.con);
#Override
protected void onPreExecute() {
JSONParsingDialog.setMessage("Preparing data...");
JSONParsingDialog.setCanceledOnTouchOutside(false);
JSONParsingDialog.setCancelable(false);
JSONParsingDialog.show();
}
#Override
protected ArrayList<HashMap<String, String>> doInBackground(Void... params) {
JSONParser jParser = new JSONParser();
final JSONObject json = jParser.getJSONFromUrl(url);
try {
places = json.getJSONArray(TAG_PLACES);
for (int i = 0; i < places.length(); i++) {
JSONObject c = places.getJSONObject(i);
String name = c.getString(TAG_PLACE_NAME);
String category = c.getString(TAG_PLACE_CATEGORY);
String distance = c.getString(TAG_PLACE_DISTANCE);
String travel_time = c.getString(TAG_TRAVEL_TIME);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_PLACE_NAME, name);
map.put(TAG_PLACE_CATEGORY, category);
map.put(TAG_PLACE_DISTANCE, distance);
map.put(TAG_TRAVEL_TIME, travel_time);
placeList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
return placeList;
}
#Override
protected void onPostExecute(ArrayList<HashMap<String, String>> result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
JSONParsingDialog.dismiss();
placeList = result;
parseJson(result);
}
}

Categories

Resources