me and my friend need help with a little application we're trying to create for a school project. Firstly, purpose of this application is finding pharmacy around where we live. These two are the sites that I'm trying to pull information from (is this called pulling?)
http://www.istanbulsaglik.gov.tr/w/nobet/liste.asp?lc=0&gun=09.05.2015
gun = day/date
lc = id of town
cs is given to a town daily and changes daily, it's just a number.
in this page.
AND/OR
http://www.nobetcieczanebul.com/
this one 'looks' much more easier to obtain required info. from.
They both contain the info that I need; name of the pharmacy, it's address and maybe phone numbers. By using JSOUP I'm hoping to parse (pull?) those information but I need help. My first priority is using 'webview'.
First we'll read cs from HTML, after that we'll put the cs into the code and call all the names, dates and addresses of pharmacy stores.
Here's my example code, this one calls id 32 town of date 05/05/2015 which contains name etc.
import android.os.AsyncTask;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import java.io.IOException;
public class MainActivity extends ActionBarActivity {
Button btnGetir;
ProgressBar pb;
TextView tv;
Button btnNobet;
TextView tvNobet;
WebView wv;
class mytask extends AsyncTask<Void,Void,Void>{
String Title;
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
pb.setVisibility(View.INVISIBLE);
tv.setText(Title);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pb.setVisibility(View.VISIBLE);
}
#Override
protected Void doInBackground(Void... params) {
try {
Document myDoc= Jsoup.connect("http://www.ticaret.edu.tr").get();
Title=myDoc.title();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
class myNobettask extends AsyncTask<Void,Void,Void>{
String Title;
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
pb.setVisibility(View.INVISIBLE);
wv.loadData(Title, "text/html", "UTF-8");
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pb.setVisibility(View.VISIBLE);
}
#Override
protected Void doInBackground(Void... params) {
try {
Document myDoc= Jsoup.connect("http://apps.istanbulsaglik.gov.tr/eczane/GetNobetciEczaneler.aspx?lc=32&gun=05.05.2015&cs=6e79f453").get();
Title=myDoc.html();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnGetir=(Button) findViewById(R.id.btnTitleGetir);
tv=(TextView)findViewById(R.id.tvSonuc);
pb=(ProgressBar) findViewById(R.id.progressBar);
btnNobet =(Button)findViewById(R.id.btnNobetci);
tvNobet=(TextView)findViewById(R.id.tvNobetci);
wv=(WebView) findViewById(R.id.webView);
btnGetir.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View v) {
mytask newtask= new mytask();
newtask.execute();
}
});
btnNobet.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View v) {
myNobettask task= new myNobettask();
task.execute();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
With JSoup you should be able to specify which CSS selectors/ HTML components you wish to parse.
Document doc = Jsoup.connect(url).get();
Elements links = doc.select("a[href]"); // This should return a collection of links.
It is possible to specify further so perhaps you wish to return a subset of all paragraph tags, you could then specify:
Document doc = Jsoup.connect(url).get();
Elements linksInPTags= doc.select("p > a[href]");
Read through the Jsoup cookbook. It's pretty clear and really helpful.
Here's a snippet of code using Google Places API that may extremely helps :
public static void makeRequest(String url)
{
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(url);
HttpResponse response;
try {
response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
String result= convertStreamToString(instream);
instream.close();
}
} catch (Exception e) {}
}
private String convertStreamToString(InputStream is) {
BufferedReader.readLine()
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
Steps to accomplish :
1 - You have to generate URL which performs your need ( as an example : https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=-33.8670522,151.1957362&radius=500&types=food&name=cruise&key=AddYourOwnKeyHere )
( a full description of creating the URL exists in the link above )
2 - It's optional but more reliable to use this method in a background thread
3 - You have to parse the response ( response can be in json or xml format you can choose it from the URL ) data to perform your needs ( you can get response fields description from the link above )
Related
Aim: Building app on Google API to fetch the data about the books the user searches
Problem Explanation:
Whenever I hit the submit Button, my app crashes.
This is my first approach in making a network request app and I need guidance.
MainActivityClass
package com.example.vidit.books;
import android.app.Activity;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText query = (EditText) findViewById(R.id.query);
Button submit= (Button) findViewById(R.id.submit);
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent= new Intent(MainActivity.this,Request.class);
intent.putExtra ( "text", query.getText().toString() );
startActivity(intent);
}
});
}
}
Second Class
package com.example.vidit.books;
import android.content.Intent;
public class Request {
Intent i = getIntent();
String text = i.getStringExtra ("text");
public static final String LOG_TAG = Request.class.getSimpleName();
String APIURL="https://www.googleapis.com/books/v1/volumes?q= " + text;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_request);
}
public void UpdateUi(Book book)
{
BookAdapter bookAdapter = new BookAdapter(this,book);
ListView listView= (ListView) findViewById(R.id.listview_all);
}
private class BookAsyncTask extends AsyncTask<URL,Void,Book>
{
#Override
protected Book doInBackground(URL... urls) {
URL url = createUrl(APIURL);
String jsonResponse = "";
try {
jsonResponse = makeHttpRequest(url);
} catch (IOException e) {
// TODO Handle the IOException
}
final Book book = extractFeatureFromJson(jsonResponse);
return book;
}
/**
* Make an HTTP request to the given URL and return a String as the response.
*/
private String makeHttpRequest(URL url) throws IOException {
String jsonResponse = "";
HttpURLConnection urlConnection = null;
InputStream inputStream = null;
try {
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setReadTimeout(10000 /* milliseconds */);
urlConnection.setConnectTimeout(15000 /* milliseconds */);
urlConnection.connect();
if(urlConnection.getResponseCode()==200) {
inputStream = urlConnection.getInputStream();
jsonResponse = readFromStream(inputStream);
}
} catch (IOException e) {
// TODO: Handle the exception
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (inputStream != null) {
// function must handle java.io.IOException here
inputStream.close();
}
}
return jsonResponse;
}
/**
* Convert the {#link InputStream} into a String which contains the
* whole JSON response from the server.
*/
private String readFromStream(InputStream inputStream) throws IOException {
StringBuilder output = new StringBuilder();
if (inputStream != null) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, Charset.forName("UTF-8"));
BufferedReader reader = new BufferedReader(inputStreamReader);
String line = reader.readLine();
while (line != null) {
output.append(line);
line = reader.readLine();
}
}
return output.toString();
}
/**
* Returns new URL object from the given string URL.
*/
private URL createUrl(String stringUrl) {
URL url = null;
try {
url = new URL(stringUrl);
} catch (MalformedURLException exception) {
Log.e(LOG_TAG, "Error with creating URL", exception);
return null;
}
return url;
}
private Book extractFeatureFromJson(String bookJSON) {
try {
JSONObject baseJsonResponse = new JSONObject(bookJSON);
JSONArray items = baseJsonResponse.getJSONArray("items");
// If there are results in the features array
for(int i=0;i<10;i++)
{
JSONObject firstFeature = items.getJSONObject(i);
JSONArray author=firstFeature.getJSONArray("author");
for(int j=0;j<author.length();j++)
{
JSONObject authorFeature=author.getJSONObject(j);
}
String title = items.getString(Integer.parseInt("title"));
// Create a new {#link Event} object
return new Book(title,author);
}
} catch (JSONException e) {
Log.e(LOG_TAG, "Problem parsing the earthquake JSON results", e);
}
return null;
}
}
}
BookAdapter Class:
package com.example.vidit.books;
import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.util.List;
public class BookAdapter extends ArrayAdapter<Book> {
public BookAdapter(Activity context, Book book)
{
super(context,0, (List<Book>) book);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View listItemView = convertView;
if(listItemView == null) {
listItemView = LayoutInflater.from(getContext()).inflate(
R.layout.list_item, parent, false);
}
Book cbook=getItem(position);
TextView title = (TextView) listItemView.findViewById(R.id.title);
title.setText(cbook.getmTitle());
TextView author=(TextView) listItemView.findViewById(R.id.author);
author.setText((CharSequence) cbook.getmAuthor());
return listItemView;
}
}
Showing error in statement:
String text = i.getStringExtra ("text");
Need guidance
I don't know how your code gets compiled when you have overridden onCreate() in Request class and the Request class isn't extending Activity or AppCompatActivity.
Secondly, this line :
Intent i = getIntent();
String text = i.getStringExtra ("text");
should be inside the onCreate() method.
Showing error in statement : String text = i.getStringExtra ("text");
Request for Guidance
Well you need to get the data passed inside onCreate like below.
String APIURL;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_request);
Bundle bundle = getIntent().getExtras();
String text = bundle.getString("text");
APIURL="https://www.googleapis.com/books/v1/volumes?q= " + text;
}
And although you have the asyncTask class i can't see where exactly you execute the class. You need to do that inside onCreate as well.
Try moving this code to your onCreate method
Intent i = getIntent();
String text = i.getStringExtra ("text");
The intent extras is not available in the constructor for your Request class.
Scenario
Users have to login to the server with this app. Later in the app we need to check their login status against the server. We used to do this by keeping track of the last used HttpClient. Recently we switched to HttpUrlConnection but the so-called persistent connections are not working.
Question
I wrote this test app to see if the connections were persistent. I get xml back from both URLs but the connection is not behaving like it's consistent. How can I get this to work?
Note: Everything works as expected if you go to the Login url in a browser and then go to the GetUserInfo url in the same browser.
MainActivity.java
package com.mediajackagency.test;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
public class MainActivity extends AppCompatActivity {
public Button signInBtn = null;
public Button getUserInfoBtn = null;
public TextView xmlTextView = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
this.xmlTextView = (TextView)findViewById(R.id.xmlTxtView);
this.signInBtn = (Button)findViewById(R.id.signInBtn);
this.signInBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AsyncTask task = new AsyncTask() {
#Override
protected Object doInBackground(Object[] params) {
String xml = loadUrl("https://www.fake.site/Login?userName=test&password=pass123");
return xml;
}
#Override
protected void onPostExecute(Object o) {
super.onPostExecute(o);
xmlTextView.setText(o.toString());
}
};
task.execute();
}
});
this.getUserInfoBtn = (Button)findViewById(R.id.getUserInfoBtn);
this.getUserInfoBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AsyncTask task = new AsyncTask() {
#Override
protected Object doInBackground(Object[] params) {
String xml = loadUrl("https://www.fake.site/GetCurrentUser");
return xml;
}
#Override
protected void onPostExecute(Object o) {
super.onPostExecute(o);
xmlTextView.setText(o.toString());
}
};
task.execute();
}
});
}
public String loadUrl(String url) {
URI uri = MainActivity.encodeUrl(url);
Log.i("XMLParser", "Get URL: " + url);
String xml = null;
URL link;
BufferedReader reader = null;
StringBuilder stringBuilder = null;
InputStream is = null;
HttpURLConnection connection = null;
try {
link = new URL(url);
connection = (HttpURLConnection) link.openConnection();
connection.setRequestMethod("GET");
connection.connect();
is = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(is));
stringBuilder = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
stringBuilder.append(line + "\r");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
if(reader != null) reader.close();
} catch (Exception e) {
e.printStackTrace();
}
try {
if(is != null) is.close();
} catch (Exception e) {
e.printStackTrace();
}
try {
if(connection != null) connection.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
}
try {
xml = stringBuilder.toString();
} catch(Exception e) {
e.printStackTrace();
}
return xml;
}
public static URI encodeUrl(String url) {
URL urlObject;
URI uri = null;
try {
urlObject = new URL(url);
uri = new URI(urlObject.getProtocol(), urlObject.getUserInfo(), urlObject.getHost(),
urlObject.getPort(), urlObject.getPath(), urlObject.getQuery(), urlObject.getRef());
} catch (Exception e) {
e.printStackTrace();
}
return uri;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Solved With Cookies
After days / hours of working on this I found that persistent connections (http.keepalive) with HttpUrlConnection is not all it's cracked up to be:
1) You need to make sure the InputStream and HttpUrlConnection are closed before you can reuse the connection and even then it may not always be reusable.
2) Open TCP connections can be resource hogs.
After finding & testing the idea of using cookies with HttpUrlConnection I decided to go that route as it's fundamentally more sound and performs better than my original idea.
I have a method that should actually read the data from the web and returns the content as a String, but it is not working.I would be glad if you can help me out! I don't know where I screwed up. I added the INTERNET uses permission in the manifest file but doesn't work. Well, I tested on the emulator only.
public String getInternetData() throws Exception {
BufferedReader in = null;// read info
String response = null;
try {
HttpClient client = new DefaultHttpClient(); // default client
// process application to handle data from web
URI website = new URI("https://www.random.com");
// get information from web
HttpGet request = new HttpGet(); // get data
InputStream inputStream = null;
request.setURI(website);// connected and request
// respons
HttpResponse httpResponse = client.execute(request);
int statutCode = httpResponse.getStatusLine().getStatusCode();
int length = (int) httpResponse.getEntity().getContentLength();
inputStream = httpResponse.getEntity().getContent();
Reader reader = new InputStreamReader(inputStream, "UTF-8");
int inChar;
StringBuffer stringBuffer = new StringBuffer();
while ((inChar = reader.read()) != -1) {
stringBuffer.append((char) inChar);
}
response = stringBuffer.toString();
} finally {
}
return response;
}
I checked your code and it's working. I'm not sure if you are establishing a connection on your EDT or not but here's a template that's working with your code. Btw your link doesn't have a SSL, you need to connect to http.
package com.example.stackover;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URI;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.Activity;
import android.app.Fragment;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
(new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
try {
getInternetData();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}).execute();
return rootView;
}
public void getInternetData() throws Exception {
BufferedReader in = null;// read info
String response = null;
try {
HttpClient client = new DefaultHttpClient(); // default client
// process application to handle data from web
URI website = new URI("http://www.random.com");
// get information from web
HttpGet request = new HttpGet(); // get data
InputStream inputStream = null;
request.setURI(website);// connected and request
// respons
HttpResponse httpResponse = client.execute(request);
int statutCode = httpResponse.getStatusLine().getStatusCode();
int length = (int) httpResponse.getEntity().getContentLength();
inputStream = httpResponse.getEntity().getContent();
Reader reader = new InputStreamReader(inputStream, "UTF-8");
int inChar;
StringBuffer stringBuffer = new StringBuffer();
while ((inChar = reader.read()) != -1) {
stringBuffer.append((char) inChar);
}
response = stringBuffer.toString();
} finally {
}
Log.v("Information", response);
}
}
}
I am new to android . I am troubling during 2 weeks with an simple android apps which I am developing. In my app , I am trying to fetch a simple text from php . But every time when I try to launch the app it crashed. My code is below
package com.example.test;
import java.io.IOException;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.TextView;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://logger.net46.net/android/hello.php");
try {
HttpResponse response = httpclient.execute(httppost);
final String str = EntityUtils.toString(response.getEntity());
TextView tv = (TextView) findViewById(R.id.textView1);
tv.setText(str);
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
I can not finding out where is my problem. Please someone help me.
You are probably getting NetWorkOnMainThreadException. You should use a Thread or AsyncTask for making the http post request and update ui on the ui thread.
Example:
public class MainActivity extends Activity {
TextView tv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView) findViewById(R.id.textView1);
new TheTask().execute();
}
class TheTask extends AsyncTask<Void,Void,String>
{
#Override
protected String doInBackground(Void... params) {
String str = null;
try
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://logger.net46.net/android/hello.php");
HttpResponse response = httpclient.execute(httppost);
str = EntityUtils.toString(response.getEntity());
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return str;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
tv.setText(result);
}
}
}
Snap
I'm new to android and I hope someone could help me here. I have an activity Faculty and a button.
This is my XML layout browse_faculty:
<Button
android:onClick="searchFSTEHandler"
android:id="#+id/bFSTE"
android:layout_width="220dp"
android:layout_height="80dp"
android:layout_alignLeft="#+id/bFBE"
android:layout_below="#+id/bFBE"
android:layout_marginTop="20dp"
android:text="#string/fste" />
and this is my Faculty Activity which displays the buttons:
I use Intent to view ListView
public class Faculty extends Activity{
#Override
protected void onCreate(Bundle BrowseFaculty) {
// TODO Auto-generated method stub
super.onCreate(BrowseFaculty);
setContentView(R.layout.browse_faculty);
}
//on the XML,this is the "searchFSTEHandler" i want to use to show ListView
public void searchFSTEHandler(View target){
Intent courseList = new Intent(this, HttpActivity.class);
startActivity(courseList);
}
}
and below is the "HttpActivity" class is the class that displays my ListView. This class read a php file which gets data from a MySQL server and converts to JSON data then parses it into a array list.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.ListActivity;
import android.widget.ArrayAdapter;
public class HttpActivity extends ListActivity {
public String f1 = "FSTE";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.faculty_course);
new getHttp().execute();
getHttp test =new getHttp();
String strJsonData = test.doInBackground(f1);
// Convert String JSON data to Java class
ArrayList<Courses> arrayCourse= test.parseJsonData(strJsonData);
//Create an ArrayAdapter which shows the ArrayList data
this.setListAdapter(new ArrayAdapter<Courses>(this,android.R.layout.simple_list_item_1,arrayCourse));
}
private class getHttp extends AsyncTask<String, Void, String> {
public getHttp() {
}
#Override
protected String doInBackground(String... faculty) {
InputStream is = null;
try {
URL url = new URL("http://10.0.2.2/sqlWebService.php?faculty=FSTE");
URLConnection con = url.openConnection();
con.setConnectTimeout(10000);
con.setReadTimeout(10000);
is = con.getInputStream();
BufferedReader br = new BufferedReader(
new InputStreamReader(is));
StringBuffer sb = new StringBuffer();
String str;
while ((str = br.readLine()) != null) {
sb.append(str);
}
return sb.toString();
} catch (IOException e) {
e.printStackTrace();
return "";
} finally {
try {
if (is != null)
is.close();
} catch (IOException e2) {
e2.printStackTrace();
}
}
}
//------------------------------------------------------
private ArrayList<Courses> parseJsonData(String strJson) {
ArrayList<Courses> Course = new ArrayList<Courses>();
try {
// Generate JSONArray object by JSON String data
JSONArray arr = new JSONArray(strJson);
//from the JSONArray, get one element (row) of JSONData
for (int i = 0; i < arr.length(); i++) {
//Get JSON Object which is one element of the array
JSONObject ob = arr.getJSONObject(i);
Courses exam = new Courses();
//get the value by key, and set to exam class
exam.setCode(ob.optString("code"));
//save exam class to exam array list
Course.add(exam);
}
} catch (JSONException e) {
e.printStackTrace();
}
return Course;
}
}
}
The application crashes as soon as I click on the button and gives a error:
"android.os.NetworkOnMainThreadException"
Help Please !
The problem that you are having is network operation like what you are trying to do cannot and should not be performed on the main UI thread. Doing so will lead to an ANR (Android Not Responding), which is exactly the kind of error you are getting just now. What you want to do is move your code to a separate thread or to an AsyncTask that will perform this action in the background on a different thread using the doInBackground() method which does not have access to your views on the main UI thread. For example,
private class ExampleOperation extends AsyncTask<String, Void, String> {
public ExampleOperation() { //ctor }
#Override
protected void onPreExecute() {
//things that you want to initialize and maybe show dialog to user.
}
#Override
protected String doInBackground(String... params) {
//this is where you perform that network related operation.
}
#Override
protected void onPostExecute(String result) {
//this is where get the results from the network related task.
}
#Override
protected void onProgressUpdate(Void... values) {
//you can update your progressbar if any; otherwise omit method.
}
}
Then all you have to do is call the AsyncTask where ever you want to use it: new ExampleOperation().execute();
You can't make HTTP calls in the main thread, they take too long and would make the UI unresponsive. You need to do it in an AsyncTask.