in AsyncTask i want the data in list view - android

hi friends i just want the data show in a list view i using async task and i complete get the data in json and filtering it by id and title now i show id and title in a listview can you help me thanks in advance
public class runActivity extends Activity implements OnClickListener {
String returnString="";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
findViewById(R.id.my_button).setOnClickListener(this);
}
#Override
public void onClick(View arg0) {
Button b = (Button)findViewById(R.id.my_button);
b.setClickable(false);
new LongRunningGetIO().execute();
}
private class LongRunningGetIO extends AsyncTask <Void, Void, String> {
protected String getASCIIContentFromEntity(HttpEntity entity) throws IllegalStateException, IOException {
InputStream in = entity.getContent();
StringBuffer out = new StringBuffer();
int n = 1;
while (n>0) {
byte[] b = new byte[4096];
n = in.read(b);
if (n>0) out.append(new String(b, 0, n));
}
return out.toString();
}
#Override
protected String doInBackground(Void... params) {
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpGet httpGet = new HttpGet("http://192.168.1.156/recess/document/document.json");
HttpClient client = new DefaultHttpClient();
HttpResponse response=null;
try{
response = client.execute(httpGet);}
catch(Exception e){}
System.out.println(response.getStatusLine());
String text = null;
try {
response = httpClient.execute(httpGet, localContext);
HttpEntity entity = response.getEntity();
text = getASCIIContentFromEntity(entity);
} catch (Exception e) {
return e.getLocalizedMessage();
}
String var =text;
try{
JSONObject jObj = new JSONObject(var);
JSONArray jArray = jObj.getJSONArray("document");
for(int i=0;i<jArray.length();i++){
JSONObject json_data = jArray.getJSONObject(i);
Log.i("log_tag","id: "+json_data.getString("id")+
", title: "+json_data.getString("title")
);
returnString += "\n" +"id:"+ json_data.getString("id")+" "+"Title:"+ json_data.getString("title");
}
}
catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
}
return returnString;
}
protected void onPostExecute(String results) {
if (results!=null) {
ListView listView = (ListView) findViewById(R.id.mylist);
listView.setFilterText(results);
}
Button b = (Button)findViewById(R.id.my_button);
b.setClickable(true);
}
}
}

You will need to build an Array to use with ListAdapter.
Here is a guide from Google: http://developer.android.com/resources/tutorials/views/hello-listview.html

I think the best solution would be to create a Handler in your activity. You can then send a message to the handler and get the data and put it in the ListView.

In doInBackground "for" loop just either create the array of your data or put data in Array list of object (then need to write custom adapter)
for
1- option
http://www.java-samples.com/showtutorial.php?tutorialid=1516
http://www.ezzylearning.com/tutorial.aspx?tid=1659127&q=binding-android-listview-with-string-array-using-arrayadapter
For
2- option
http://www.ezzylearning.com/tutorial.aspx?tid=1763429&q=customizing-android-listview-items-with-custom-arrayadapter

Related

How to synchronize android spinner of two different activity

I have two activity.Both activity loaded the same data in the spinner from server.and both activity populate properly.I'm not getting proper idea that change in one spinner item position also display the same spinner's item when switch to other activity.How to synchronize both spinners of two different activities.
private class BackTask extends AsyncTask<Void,Void,Void> {
ArrayList<String> list;
protected void onPreExecute(){
super.onPreExecute();
list=new ArrayList<>();
}
protected Void doInBackground(Void...params){
InputStream is=null;
String result="";
try{
HttpClient httpclient=new DefaultHttpClient();
HttpPost httppost= new HttpPost("http://my_url/Service.asmx/GetServiceList");
HttpResponse response=httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
// Get our response as a String.
is = entity.getContent();
}catch(IOException e){
e.printStackTrace();
}
//convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"utf-8"));
String line = null;
while ((line = reader.readLine()) != null) {
result+=line;
}
is.close();
//result=sb.toString();
}catch(Exception e){
e.printStackTrace();
}
// parse json data
try{
JSONArray jArray =new JSONArray(result);
for(int i=0;i<jArray.length();i++){
JSONObject jsonObject=jArray.getJSONObject(i);
// add interviewee name to arraylist
list.add(jsonObject.getString("ServiceName"));
}
}
catch(JSONException e){
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Void result){
listItems.addAll(list);
adapter.notifyDataSetChanged();
}
}
public class StaticResources
{
private List<String> sDataSource = new ArrayList<String>();
public List<String> getDataSource() {...}
public void setDataSource(..) {...}
}
In both activities, refer to StaicResources.getDataSource(), that is it.
Try with this way
public static ArrayList listid,listdata;
onPostExecute(){
try{
JSONArray jarrvideos=new JSONArray(responcedata);
for(int i=0;i<jarrvideos.length();i++){
JSONObject jobj = jarrvideos.getJSONObject(i);
listid.add(jobj.getString("id"));
listdata.add(jobj.getString("id"));
}
BindSpinnerData();
}catch(Exception e){
e.printStackTrace();
}
}
private void BindSpinnerData() {
ArrayAdapter<String> spinnerLocation = new
ArrayAdapter<String(MedicalSurgical.this, R.layout.spinneritem, listdata);
spinnerLocation.setDropDownViewResource(R.layout.spinnerpopupblack);
spnDatasecond.setAdapter(spinnerLocation);
}
now it will display your first activity dpinner data if you need another activity same spinner data then you need to access listid,listdata array list in another class
for Accessing classname.listid or classname.listdata

NetworkOnMainThread Exception - parsing data the right way

iam developing an android app for parsing a json data set into my app. But everytime iam getting a NetworkOnMainThred exception:
android.os.NetworkOnMainThreadException
On this line:
HttpResponse response = httpclient.execute(httppost);
After that ive tried fixing it by puttin the progress in an AsyncTask Inner Class. But that has no effect iam getting the same error. Is the AsyncTask really essential?
Here the whole context:
question.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Connector db = new Connector();
db.executeAction();//calls AsyncTask
}
});
public class Connector extends Activity {
View rootView;
ArrayList<String> resultset = new ArrayList<String>();
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
public void executeAction() {
new LongOperation().execute();
}
private class LongOperation extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
testDB2();
return null;
}
public void testDB2() {
String result = "";
//the year data to send
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("year", "1980"));
//http post
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://quizmaster.esy.es/db_con.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
//(TextView)rootView.findViewById(R.id.question)
Log.e("log_tag", "Error converting result " + e.toString());
}
ArrayList<String> resultset = new ArrayList<String>();
//parse json data
try {
JSONArray jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
resultset.add(String.format(json_data.getString("Frage")));
Log.i("log_tag", "id: " + json_data.getInt("ID") +
", Frage: " + json_data.getString("Frage")
);
}
}
catch(JSONException e)
{
Log.e("log_tag", "Error parsing data " + e.toString());
}
}
#Override
protected void onPostExecute(String result) {
}
#Override
protected void onPreExecute() {
}
#Override
protected void onProgressUpdate(Void... values) {
}
}
}
Invocation:
public class Connector extends Activity {
View rootView;
ArrayList<String> resultset = new ArrayList<String>();
/** Called when the activity is first created. */
#Override public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
public void executeAction() {
new LongOperation().doInBackground();
}
Your onPostExecute() contains a call to testDB2(). onPostExecute() is executed on the main thread. Thus the exception.
Further, you never call doInBackground() directly. Instead, you would invoke the AsyncTask as:
new LongOperation().execute();

How to put data in listview which received using AsyncTask?

I am successfully retrieving but unable to put data into listview. how to update ui thread
after retrieving data.
here is the class of asynctask that retrieves data
I tried to update in onPostExecute but couldn't succeed.
class GetJson extends AsyncTask<String, Integer, ArrayList<RowItem>> {
ArrayList<RowItem> rowItems = new ArrayList<RowItem>();
//ArrayList<ArrayList<String>> fullscreens = new ArrayList<ArrayList<String>>() ;
public AsyncResponse delegate = null;
private CustomListViewAdapter arrayadapter;
private ProgressDialog pDialog;
private Context Mycontext;
private ArrayList<String> alist;
private ListView listView;
public GetJson(Context cnxt,ArrayList<String> alist, CustomListViewAdapter adapt,ListView listView) {
Mycontext = cnxt ;
//this.rowItems = rowItems;
this.alist = alist;
this.listView = listView;
}
#Override
protected void onPreExecute() {
// Showing progress dialog before sending http request
this.pDialog = new ProgressDialog(Mycontext);
this.pDialog.setMessage("Please wait..");
this.pDialog.setIndeterminate(true);
this.pDialog.setCancelable(false);
this.pDialog.show();
//alist.add("fifa");
}
#Override
protected ArrayList<RowItem> doInBackground(String... passing) {
here i am recieving data
return rowItems;
}
#Override
protected void onPostExecute(ArrayList<RowItem> Items) {
super.onPostExecute(Items);
this.pDialog.dismiss();
}
}
I laso tried runuithread in doinBackgroung method
there also i am getting runtime errors
here is my code
protected Void doInBackground(Void... unused) {
runOnUiThread(new Runnable() {
public void run() {
String result = null;
InputStream is = null;
JSONObject json_data=null;
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
JSONArray ja = new JSONArray();
List<NameValuePair> params = new LinkedList<NameValuePair>();
for(String s : alist)
{
Log.d("s",s);
params.add(new BasicNameValuePair("list[]",s));
}
try{
// 1. create HttpClient
HttpClient httpclient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
// 2. make POST request to the given URL
HttpGet httpPost = new HttpGet("http://10.0.3.2/infogamma/getapps.php?"+paramString);
// 4. convert JSONObject to JSON to String
String json = ja.toString();
HttpResponse response = httpclient.execute(httpPost);
HttpEntity entity = response.getEntity();
//String json = EntityUtils.toString();
is = entity.getContent();
// Log.d("response", ");
}
catch(Exception e){
Log.i("taghttppost",""+e.toString());
}
//parse response
try
{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"UTF-8"));
StringBuilder stringbuilder = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
stringbuilder.append(line + "\n");
}
is.close();
result = stringbuilder.toString();
Log.d("ans",result);
}
catch(Exception e)
{
Log.i("tagconvertstr",""+e.toString());
}
//get json data
try{
//JSONObject json = new JSONObject(result);
JSONArray jArray = new JSONArray(result);
Log.d("app_lentgh", Integer.toString(jArray.length()));
for(int i=0;i<jArray.length();i++)
{
json_data = jArray.getJSONObject(i);
// this.donnees.add("title: "+ json_data.getString("title") + " appid: " + json_data.getString("appid") );
try{
//commmand http
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet("http://10.0.3.2/infogamma/getAppDetails.php?appid="+json_data.getString("appid"));
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
//String json = EntityUtils.toString();
is = entity.getContent();
// Log.d("response", ");
}
catch(Exception e){
Log.i("taghttppost",""+e.toString());
}
//parse response
try
{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"UTF-8"));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
is.close();
result = sb.toString();
Log.d("ans",result);
}
catch(Exception e)
{
Log.i("tagconvertstr",""+e.toString());
}
ArrayList<String> screenitem = new ArrayList<String>();
try{
JSONObject j = new JSONObject(result);
screenitem.add(j.getString("scr1"));
screenitem.add(j.getString("scr2"));
screenitem.add(j.getString("scr3"));
// this.fullscreens.add(screenitem);
// RowItem(ImageView imageId, String title, String desc,String catgs,String downloads,String rating,String discription)
RowItem item = new RowItem(j.getString("coverimage"), j.getString("title"), j.getString("category"),j.getString("downloads"),j.getString("rating"),
j.getString("scr1"),j.getString("scr2"),j.getString("scr3"),j.getString("discription"),j.getString("developer"),j.getString("price")
,json_data.getString("appid"));
rowItems.add(item);
}
catch(JSONException e){
Log.i("tagjsonexp",""+e.toString());
}
//SharedPreferences.Editor editor = ((Activity) Mycontext).getPreferences(Mycontext.MODE_PRIVATE).edit();
//editor.;
//editor.commit();
//Log.i("title",json_data.getString("title"));
}
}
catch(JSONException e){
Log.i("tagjsonexp",""+e.toString());
} catch (ParseException e) {
Log.i("tagjsonpars",""+e.toString());
}
adapt = new CustomListViewAdapter(getApplicationContext(),
R.layout.list_item, rowItems);
listView.setAdapter(adapt);
}});
return (null);
}
You can populate the list view from doInBackground by this code
runOnUiThread(new Runnable() {
public void run() {
//set listview Adapter here
}
});
this thing is not preferable. One more thing you can do is create a class which can hold the data you want to show on the item of a list and pass the array of that class object to onPostExecute method from where you can handle the UI thread.
Do it in onPostExecute() or if you want to add them from doInBackground() instantly, do it using runOnUiThread().
Edit:
After reading your comments, You are using CustomListViewAdapter, do you have a constructor with Context,int,ArrayList<String> as parameters in your adapter class?

How to make a TextView show a value from a AsynTask class

I have an AsynTask which retrieve data from a web service and with this data to be viewed on the UI. So, in my MainActivity, I have a textView.
This is the data I received from the webservice:
{"name":"ezio","country":"italy"}{"name":"fufu","country":"tutu"}{"name":"chikaka","country":"aceVentura"}
The problem is, I do not know how to set the textView with the value of 'result' from the ClientConnection class. When I run the application, the textView is empty.
public class ClientConnection extends AsyncTask {
public static final String URL = "http://192.168.0.15/test.php";
static JSONObject jObj = null;
public static String result = "";
#Override
protected String doInBackground(Void... voids) {
// public JSONObject connect(){
try{
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(URL);
HttpResponse response = httpClient.execute(httpGet);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
Log.e("HTTPStatus error:","Status not okay");
}
InputStream in = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(in, "iso-8859-1"), 8);
StringBuilder str = new StringBuilder();
String line = null;
while((line = reader.readLine()) != null){
str.append(line + "\n");
}
in.close();
result = str.toString();
JSONObject jsonObject = convertToJson(result);
// jsonObject.get()
//result = jsonObject.getString("name");
//JSONArray google = jsonObject.getJSONArray("");
} catch (Exception e) {
//Toast toast = Toast.makeText(null, e.getMessage(), Toast.LENGTH_LONG);
Log.e("Error","don't know what exception though");
}
return result;
}
private JSONObject convertToJson(String test){
JSONArray clients = new JSONArray();
try{
jObj = new JSONObject(test);
}catch (JSONException e){
Log.e("JSON Parser", "Error parsing data" + e.toString());
}
return jObj;
}
public String getResult(){
return result;
}
public JSONObject getjObj(){
return jObj;
}
}
And this is the Main Activity
public class MyActivity extends Activity {
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final TextView textView = (TextView) findViewById(R.id.textViewTest);
ListView listView = (ListView) findViewById(R.id.listView);
Button buttonConnect = (Button) findViewById(R.id.buttonConnect);
final ClientJSONParsingActivity clientJSONParsingActivity = new ClientJSONParsingActivity();
buttonConnect.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new ClientConnection().execute();
textView.setText(new ClientConnection().getResult());
}
});
}
}
Thank you for your help
You can display the result in the onPostExecute in the AsyncTask.
You should update textview in your asynctask. onPostExecute() method runs on UI thread
protected void onPostExecute(String result) {
textView.setText(result);
}
Pass the text view as an argument to the asynctask and set it in onPostExecute. On my mobile so no code, sorry ;-)
add this code under your doinbackground;
protected void onPostExecute(Long result) {
(find your text view here from the context where textview it is)
textView.setText(result);
}

async task issue in json format

i have a problem while im get the data from the server in text i can't converted into json object can not be converted into json array i just get the title and author from the database and show in list view
{"document":[{"id":"1","title":"complete refrence of android",
"author":"parag vyas","description":"lnvkzxhbkgbovdghognsdkhogjhlldnglj"}]}
plz help me
public class showalbooks extends Activity {
ArrayList<String> mylist = new ArrayList<String>();
String returnString="";
ListView listView ;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.showalbooks);
listView = (ListView) findViewById(R.id.mylist);
new LongRunningGetIO().execute();
}
private class LongRunningGetIO extends AsyncTask <Void, Void, String> {
protected String getASCIIContentFromEntity(HttpEntity entity) throws IllegalStateException, IOException {
InputStream in = entity.getContent();
StringBuffer out = new StringBuffer();
int n = 1;
while (n>0) {
byte[] b = new byte[4096];
n = in.read(b);
if (n>0) out.append(new String(b, 0, n));
}
return out.toString();
}
#Override
protected String doInBackground(Void... params) {
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpGet httpGet = new HttpGet("http://192.168.1.156/recess/document/document.json");
HttpClient client = new DefaultHttpClient();
HttpResponse response=null;
try{
response = client.execute(httpGet);
}
catch(Exception e){}
System.out.println(response.getStatusLine());
String text = null;
try {
response = httpClient.execute(httpGet, localContext);
HttpEntity entity = response.getEntity();
text = getASCIIContentFromEntity(entity);
} catch (Exception e) {
return e.getLocalizedMessage();
}
String var =text;
try{
JSONArray jArray = new JSONArray(var);
for(int i=0;i<jArray.length();i++){
JSONObject json_data = jArray.getJSONObject(i);
Log.i("log_tag","id: "+json_data.getString("id")+
", title: "+json_data.getString("title")
);
returnString += "\n" +"id:"+ json_data.getString("id")+" "+"Title:"+ json_data.getString("title");
}
}
catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
}
listView.setFilterText(returnString);
return returnString;
}
protected void onPostExecute(String results) {
if (results!=null) {
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View listview,
int documentid, long documenttitle) {
// TODO Auto-generated method stub
}
});
}
}}}
The JSON array is enclosed by a JSON object, and has the id "document".
instead of:
JSONArray jArray = new JSONArray(var);
You should have:
JSONObject jObj = new JSONObject(var);
JSONArray jArray = jObj.getJSONArray("document");

Categories

Resources