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();
Related
I have a listview populated by the data from mysql database. It works fine but when I select an item then press back , the previous listview fecth again data from database that duplicates the items in my listview.
Here's is my code :
public class CityPage extends Activity{
Activity context;
HttpPost httppost;
StringBuffer buffer;
HttpResponse response;
HttpClient httpclient;
ProgressDialog pd;
CityAdapter cityAdapter;
ListView listCity;
ArrayList<City> records;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_city_page);
context = this;
records = new ArrayList<City>();
listCity = (ListView) findViewById(R.id.cities);
cityAdapter = new CityAdapter(context, R.layout.city_layout, R.id.city_name, records);
listCity.setAdapter(cityAdapter);
listCity.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent myIntent = new Intent(view.getContext(),City_attractions.class);
Toast.makeText(CityPage.this, "Opening", Toast.LENGTH_LONG).show();
String info1 = records.get(position).getCityName();
String info2 = records.get(position).getDescription();
myIntent.putExtra("info1", info1);
myIntent.putExtra("info2", info2);
startActivity(myIntent);
}
});
}
#Override
protected void onStart() {
super.onStart();
fetchCity fetch = new fetchCity();
fetch.execute();
}
private class fetchCity extends AsyncTask<Void, Void, Void> {
protected void onPreExecute() {
super.onPreExecute();
}
protected Void doInBackground(Void... params) {
InputStream is = null;
String result = "";
try {
httpclient = new DefaultHttpClient();
httppost = new HttpPost("http://iguideph-001-site1.btempurl.com/getcity.php");
response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
// Get our response as a String.
is = entity.getContent();
} catch (Exception e) {
if (pd != null)
pd.dismiss(); //close the dialog if error occurs
Log.e("ERROR", e.getMessage());
}
//convert response to string
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "utf-8"), 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) {
Log.e("ERROR", "Error converting result " + e.toString());
}
//parse json data
try {
// Remove unexpected characters that might be added to beginning of the string
result = result.substring(result.indexOf(""));
JSONArray jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
City p = new City();
p.setCityName(json_data.getString("place_name"));
p.setDescription(json_data.getString("description"));
records.add(p);
}
} catch (Exception e) {
Log.e("ERROR", "Error pasting data " + e.toString());
}
return null;
}
protected void onPostExecute(Void result) {
if (pd != null) pd.dismiss(); //close dialog
Log.e("size", records.size() + "");
cityAdapter.notifyDataSetChanged(); //notify the ListView to get new records
}
}
}
try remove those lines from onstart() and put them inside oncreate() function
fetchCity fetch = new fetchCity();
fetch.execute();
Good luck !
I am working with android.I had created an app in which json data is loaded in asynchronous task and do something in the onpost execute method. I used the following code
public class Feat extends Activity {
JSONArray user = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AsyncTask<Void, Void,Void> t = new AsyncTask<Void, Void,Void>()
{
#Override
protected Void doInBackground(Void... arg0) {
try {
HttpClient httpclient2 = new DefaultHttpClient();
HttpPost httppost2 = new HttpPost("MY URL");
HttpResponse response2 = httpclient2.execute(httppost2);
HttpEntity entity2 = response2.getEntity();
is = entity2.getContent();
Log.e("log_tag", "connection success2222 ");
}
catch(Exception e)
{
Log.e("log_tag", "Error in http connection "+e.toString());
}
try
{
BufferedReader reader2 = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb2 = new StringBuilder();
String line = null;
while ((line = reader2.readLine()) != null)
{
sb2.append(line + "\n");
}
is.close();
result2=sb2.toString();
res=result2.substring(3);
Log.i("result",""+res);
}
catch(Exception e)
{
Log.e("log_tag", "Error converting result "+e.toString());
}
try
{
jArray2 = new JSONArray(result2);
Log.w("Lengh",""+jArray2.length());
final String imgArray[] = new String[jArray2.length()];
String name[] = new String[jArray2.length()];
for(int i=0;i<jArray2.length();i++){
JSONObject json_data2 = jArray2.getJSONObject(i);
imgArray[i] = json_data2.getString("track_url");
name[i] = json_data2.getString("campaign_name");
} }
catch(JSONException e)
{
Log.e("log_tag", "Error parsing data "+e.toString());
}
return jArray2;
}
#Override
protected void onPostExecute(Void result) {
setContentView(R.layout.ss);
t1=(TextView)findViewById(R.id.cat1);
}
};
t.execute();
}
Now how can i use return type of do in background in post execute method ??
This is the class I have used:
public class GetJSON extends AsyncTask<JSONObject, Integer, JSONObject> {
#Override
protected JSONObject doInBackground(JSONObject... arg0) {
//All the try, catch etc.
//be sure to end it with
return (yourJSONObject)
}
protected void onPostExecute(JSONObject result) {
//Your code
}
read json inside postexecute() like this
public class HttpAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
return GET(urls[0]);
}
// onPostExecute displays the results of the AsyncTask.
#Override
protected void onPostExecute(String result) {
Toast.makeText(getBaseContext(), "Received!", Toast.LENGTH_LONG).show();
try {
JSONObject json = new JSONObject(result);
JSONArray articles = json.getJSONArray("images");
image_first =new String[json.getJSONArray("images").length()]; //initializtion
image_second =new String[json.getJSONArray("images").length()];
for(int i=0;i<json.getJSONArray("images").length()/2;i++){
image_first[i] = (articles.getJSONObject(i).optString("image_first"));
}
for(int j=json.getJSONArray("images").length()/2;j<json.getJSONArray("images").length();j++){
image_second[j]= (articles.getJSONObject(j).optString("image_second"));
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
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);
}
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
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");