Main thread freezes when fetching data from URL on Async Task - android

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

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 auto-refresh listview items

I'm really new to android programming, I successfully get data from server and then populated into a listview. But how do I auto-refresh the listview items within certain amount of time? There maybe new items coming in from the server when I refresh the new items may appear.
Here's my code of retrieving data from server:
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
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;
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);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
oslist = new ArrayList<HashMap<String, String>>();
Btngetdata = (Button)getView().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> {
public ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
number = (TextView)getView().findViewById(R.id.number);
info = (TextView)getView().findViewById(R.id.info);
remark = (TextView)getView().findViewById(R.id.remark);
statuss = (TextView)getView().findViewById(R.id.statuss);
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Getting Data ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
public JSONObject doInBackground(String... args) {
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url);
return json;
}
#Override
public 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)getView().findViewById(R.id.list);
ListAdapter adapter = new SimpleAdapter(getActivity(), oslist,
R.layout.list_view,
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(getActivity(), "You Clicked at "+oslist.get(+position).get("name"), Toast.LENGTH_SHORT).show();
String numberr = oslist.get(position).get("phonenumber");
Intent intent = new Intent(getActivity(), ThreeButton.class);
intent.putExtra("key", numberr);
startActivity(intent);
}
}
);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
i would recommend you to use handler for refreshing data. i.e
final Handler handler = new Handler();
Runnable refresh = new Runnable() {
#Override
public void run() {
new JSONParse().execute();
handler.postDelayed(this, 60 * 1000);
}
};
handler.postDelayed(refresh, 60 * 1000);
this handler refresh data for every minute.
To prevent the adding the same data in list view you should use following things :
Please paste following code inside the onPost() method of the AsyncTask before for loop :
if(oslist!=null && oslist.size()>0)
oslist.clear();

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;

Listview is getting the value twice

I have a API which responds in JSON. When I clicked a button I am comfortably parse the JSON and implement it in the listview. The problem is When I go back to the previous activity and clicked the button once again I am getting the values repeat. i.e. previous values also, even I had called finish(); in on pause state of the listview activity. Following is my code.
Invoice Class
public class Invoice extends Activity{
public static ArrayList<HashMap<String, String>> ModuleName = new ArrayList<HashMap<String, String>>();
boolean tree = true;
ArrayList<String> KEY = new ArrayList<String>();
ListView mListView;
ProgressBar mProgress;
JSONObject json;
JSONArray Module_list = null;
Invoice_adapter adapter;
public static String KEY_SUCCESS = "success";
public static String KEY_ERROR = "error";
public static String KEY_ERROR_MSG = "error_msg";
public static String KEY_MODULELIST_MODULEHEADER = "moduleHeader";
public static String KEY_MODULELIST_MODULELIST = "moduleList";
public static String KEY_MODULELIST_DATAFOUND = "datafound";
public static String KEY_INVOICE_INVOICENO = "";
public static String KEY_INVOICE_SUBJECT = "";
public static String KEY_INVOICE_SALESORDER = "";
public static String KEY_INVOICE_STATUS = "";
public static String KEY_INVOICE_TOTAL = "";
public static String KEY_INVOICE_ASSIGNEDTO = "";
public static String KEY_INVOICE_RECORDID = "";
public static String KEY_INVOICE_ACTION = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_module_data);
mListView = (ListView) findViewById(R.id.module_list);
mProgress = (ProgressBar) findViewById(R.id.progressBar1);
try {
json = new ParseDATA().execute().get();
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (ExecutionException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
if (json.getString(KEY_SUCCESS) != null) {
String res = json.getString(KEY_SUCCESS);
if(Integer.parseInt(res) == 1){
String data_found = json.getString(KEY_MODULELIST_DATAFOUND);
if (data_found.equals("Data Found!")){
JSONArray array = json.getJSONArray(KEY_MODULELIST_MODULELIST);
int count1 = array.length();
String Count1 = Integer.toString(count1);
Log.d("Count_array", Count1);
JSONObject keyarray = array.getJSONObject(0);
#SuppressWarnings("rawtypes")
Iterator temp = keyarray.keys();
while (temp.hasNext()) {
String curentkey = (String) temp.next();
KEY.add(curentkey);
}
Collections.sort(KEY, String.CASE_INSENSITIVE_ORDER);
KEY_INVOICE_ACTION = KEY.get(0);
KEY_INVOICE_ASSIGNEDTO = KEY.get(1);
KEY_INVOICE_INVOICENO = KEY.get(2);
KEY_INVOICE_RECORDID = KEY.get(3);
KEY_INVOICE_SALESORDER = KEY.get(4);
KEY_INVOICE_STATUS = KEY.get(5);
KEY_INVOICE_SUBJECT = KEY.get(6);
KEY_INVOICE_TOTAL = KEY.get(7);
Log.d("Parsing Json class", " ---- KEYS---- " + KEY);
Module_list = json.getJSONArray(KEY_MODULELIST_MODULELIST);
int count = Module_list.length();
String Count = Integer.toString(count);
Log.d("Count_Module_LIST", Count);
// looping through All Contacts
for(int i = 0; i < Module_list.length(); i++){
JSONObject c = Module_list.getJSONObject(i);
// Storing each json item in variable
String mAction = c.getString(KEY_INVOICE_ACTION);
String mAssignedTo = c.getString(KEY_INVOICE_ASSIGNEDTO);
String mInvoice = c.getString(KEY_INVOICE_INVOICENO);
String mRecordid = c.getString(KEY_INVOICE_RECORDID);
String mSalesorder = c.getString(KEY_INVOICE_SALESORDER);
String mStatus = c.getString(KEY_INVOICE_STATUS);
String mSubject = c.getString(KEY_INVOICE_SUBJECT);
String mTotal = c.getString(KEY_INVOICE_TOTAL);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(KEY_INVOICE_ACTION, mAction);
map.put(KEY_INVOICE_ASSIGNEDTO, mAssignedTo);
map.put(KEY_INVOICE_INVOICENO, mInvoice);
map.put(KEY_INVOICE_RECORDID, mRecordid);
map.put(KEY_INVOICE_SALESORDER, mSalesorder);
map.put(KEY_INVOICE_STATUS, mStatus);
map.put(KEY_INVOICE_SUBJECT, mSubject);
map.put(KEY_INVOICE_TOTAL, mTotal);
// adding HashList to ArrayList
ModuleName.add(map);
}
}else
{
Toast.makeText(getApplicationContext(), "No Data", Toast.LENGTH_LONG).show();
return;
}
}
mProgress.setVisibility(View.INVISIBLE);
adapter = new Invoice_adapter(Invoice.this, ModuleName);
mListView.setAdapter(adapter);
mListView.setVisibility(View.VISIBLE);
//mListView.invalidateViews();
}
else
{
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(KEY_ERROR, "Error");
ModuleName.add(map);
//JSONObject json_user = json.getJSONObject("user");
//error_message = json_user.getString(KEY_ERROR_MSG);
}
}catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Something went wrong.Please try again.!!", Toast.LENGTH_LONG).show();
}
}
class ParseDATA extends AsyncTask<Void, String,JSONObject >
{
ProgressDialog dialog = new ProgressDialog(Invoice.this);
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
dialog.setTitle("Loading");
dialog.setIndeterminate(true);
dialog.setMessage("Please wait");
dialog.setCancelable(false);
dialog.show();
}
#Override
protected JSONObject doInBackground(
Void... params) {
// TODO Auto-generated method stub
UserFunctions userFunction = new UserFunctions();
JSONObject json = userFunction.getModuleList("1", "20", "Invoice");
return json;
}
#Override
protected void onPostExecute(JSONObject result) {
// TODO Auto-generated method stub
dialog.dismiss();
}
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
Toast.makeText(getApplicationContext(), "PAUSE STATE", Toast.LENGTH_LONG).show();
finish();
}}
Adapter class
public class Invoice_adapter extends BaseAdapter {
private Activity activity;
private ArrayList<HashMap<String, String>> data;
private static LayoutInflater inflater=null;
public Invoice_adapter(Activity a, ArrayList<HashMap<String, String>> d) {
activity = a;
data=d;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
return data.size();
}
public Object getItem(int position) {
return data.get(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.activity_module_data_detail, null);
TextView title = (TextView)vi.findViewById(R.id.textView1); // category title name
//ImageView moduleImage = (ImageView) vi.findViewById(R.id.recipe_image);
HashMap<String, String> song = new HashMap<String, String>();
song = data.get(position);
Log.i("list", ""+data.get(position));
//Log.i("list", data);
String ff = song.get(Invoice.KEY_INVOICE_SUBJECT);
title.setText(ff);
//moduleImage.setImageResource(mModuleImages[position]);
return vi;
}}
Please Help.. !! I dnt know what Is I am doing wrong.
Thanks in advance.
The problem is with the "static" key word for the ArrayList
public static ArrayList<HashMap<String, String>> ModuleName = new ArrayList<HashMap<String, String>>();
static variables are initialized only when the class is loaded, that means the value will be persisted till the end of the application process.
Either remove static keyword for array list or clear the array list before you load new data.
ModuleName.clear();

Json image cant load

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?

Categories

Resources