How to retrieve a website via HTTP? - java

i have this application force close with this code, what i do wrong?
public void buscaAno(View v){
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://sapires.netne.net/teste.php?formato=json&idade=55");
try {
HttpResponse response = httpclient.execute(httppost);
final String str = EntityUtils.toString(response.getEntity());
TextView tv = (TextView) findViewById(R.id.idade);
tv.setText(str);
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

It seems like this is onClick listener and it does a blocking operation on main thread which in turn causes ANR or NetworkOnMainThreadException. You should probably use AsyncTask or Service for your purpose.
For example, you could extend AsyncTask the following way:
private class PostRequestTask extends AsyncTask<String, Void, String> {
protected String doInBackground(String... strings) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(strings[0]);
try {
HttpResponse response = httpclient.execute(httppost);
return EntityUtils.toString(response.getEntity());
} catch (IOException e) {
//Handle exception here
}
}
protected void onPostExecute(String result) {
TextView textView = (TextView) findViewById(R.id.idade);
textView.setText(result);
}
}
And then use it like this:
public void buscaAno(View v) {
new PostRequestTask().execute("http://sapires.netne.net/teste.php?formato=json&idade=55");
}

Related

How do you store an intent into an SQL database?(Android)

Im trying to store an intent from an android app to a database and I'm having some issues converting it into a string and storing it in the database.Its connecting to the database and the id is incrementing.
Ive stored the intents inside the string.xml file like this:
<string name="key_username">username</string>
<string name="key_pet_name">pet_name</string>
I took the intent from another actvity like this:
Intent i = newIntent(Hamster.this,Death.class); i.putExtra(getString(R.string.key_username),Username); i.putExtra(getString(R.string.key_pet_name), Petname);
i.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
overridePendingTransition(0, 0);
startActivity(i);
And this is the code I'm using to connect to the database:
public class Death extends Activity {
public static String Petsname,Username ;
private ImageView dead;
private Button submit;
private TextView hamsters_death;
public static final String TAG = "Death";
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
StrictMode.setThreadPolicy(policy);
setContentView(R.layout.death);
final Intent intent = getIntent();
submit = (Button) findViewById(R.id.button);
submit.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String Username = intent.getStringExtra(getString(R.string.key_username));
String Petname = intent.getStringExtra(getString(R.string.key_pet_name));
Log.d(TAG, Username);
Log.d(TAG,Petname);
new SummaryAsyncTask().execute(new FormData());
}
});
}
}
class SummaryAsyncTask extends AsyncTask<FormData, Void, JSONArray> {
Intent intent;
public String Username;
public String Petname;
public void postData(String Username, String Petname)
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://10.0.2.2:8888/Hamster_website/hamster.php");
try{
ArrayList<NameValuePair> form_items = new ArrayList<NameValuePair>(2);
form_items.add(new BasicNameValuePair("Username", Username));
form_items.add(new BasicNameValuePair("Petname", Petname));
httppost.setEntity(new UrlEncodedFormEntity(form_items));
HttpResponse response = httpclient.execute(httppost);
}
catch(Exception e)
{
Log.e("log_tag", "Error: " + e.toString());
}
}
protected JSONArray doInBackground(FormData... params) {
postData(Username, Petname);
return null;
}
}
class FormData {
public JSONArray PostForm() {
{
String url = "http://10.0.2.2:8888/Hamster_website/hamster.php";
HttpEntity httpEntity = null;
try {
DefaultHttpClient httpClient = new DefaultHttpClient(); // Default HttpClient
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
httpEntity = httpResponse.getEntity();
} catch (ClientProtocolException e) {
// Signals error in http protocol
e.printStackTrace();
//Log Errors Here
} catch (IOException e) {
e.printStackTrace();
}
// Convert HttpEntity into JSON Array
JSONArray jsonArray = null;
if (httpEntity != null) {
try {
String entityResponse = EntityUtils.toString(httpEntity);
Log.e("Entity Response : ", entityResponse);
jsonArray = new JSONArray(entityResponse);
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
//JSONArray =
for (int i = 0; i < jsonArray.length(); i++) {
Log.d("JSON DEBUG", jsonArray.get(i).toString());
}
} catch (JSONException jse) {
jse.printStackTrace();
}
return jsonArray;
}
}
}

how read a Json file From a URL?

I wrote a program
I want download a json file from a URL and show it in a text view ..
When you click the button the program will stop after a few seconds .
I do not know what the problem is .
Please help me..
java code:
public class MainActivity extends Activity {
TextView tx;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button b=(Button)findViewById(R.id.button2);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
new GetJsonTask().execute("http://shahid.ifilmtv.ir/query/englishcurrentshows");
}
});
}
public class GetJsonTask extends AsyncTask<String, Void, String>
{
#Override
protected String doInBackground(String... urls) {
// TODO Auto-generated method stub
return getJson(urls[0]);
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
JSONArray jsonArray;
try {
jsonArray = new JSONArray(result);
JSONObject object = jsonArray.getJSONObject(1);
tx.setText(object.getString("id"));
}
catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public String getJson(String url) {
try {
InputStream inputStream = null;
DefaultHttpClient defaultHttpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = defaultHttpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
inputStream = httpEntity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
inputStream.close();
String result = sb.toString();
return result;
} catch (Exception ex) {
Toast.makeText(getApplicationContext(), "ERROR : " + ex, Toast.LENGTH_LONG).show();
return null;
}
}
}
I think the issue is in getJSON method. I have rewritten a following code. Please try this.
public String getJson(String url) {
try {
DefaultHttpClient defaultHttpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpost.setHeader("Accept", "application/json");
httpost.setHeader("Content-type", "application/json");
ResponseHandler responseHandler = new BasicResponseHandler();
Object resp = defaultHttpClient.execute(httpPost, responseHandler);
String json = resp.toString();
// create a object here if you want
JSONObject obj = new JSONObject(json);
return json;
} catch (Exception ex) {
Toast.makeText(getApplicationContext(), "ERROR : " + ex, Toast.LENGTH_LONG).show();
return null;
}
}

Why is the Progess Dialog appearing when back button is pressed?

When I go back to the previous activity by pressing the back button the progress dialog is appearing and not disappearing. When I minimize they the app the progress dialog disappears.
Here is the code for the async class
public class BackGroundTask extends AsyncTask<String, String, JSONObject> {
List<NameValuePair> postparams = new ArrayList<NameValuePair>();
private ProgressDialog pd;
String url = null;
String method = null;
Context context;
public BackGroundTask(String url, String method,
List<NameValuePair> params, Context context) {
this.url = url;
postparams = params;
this.method = method;
this.context = context;
//pd = new ProgressDialog(context);
//pd.setTitle("Processing...");
//pd.setMessage("Please wait.");
//pd.setCancelable(false);
//pd.setIndeterminate(true);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(context);
pd = ProgressDialog.show(context, "Processing...", "Please wait.", true, false);
}
#Override
protected void onPostExecute(JSONObject result) {
super.onPostExecute(result);
pd.dismiss();
}
#Override
protected JSONObject doInBackground(String... params) {
// TODO Auto-generated method stub
// Making HTTP request
try {
// Making HTTP request
// check for request method
if (method.equals("POST")) {
// request method is POST
// defaultHttpClient
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(postparams));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} else if (method == "GET") {
// request method is GET
HttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(postparams,
"utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
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();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
System.out.println(json);
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
//pd.dismiss();
// return JSON String
return jObj;
}
}
You aren't dismissing it when you finish the Activity and the task must not be done. Override finish() and dismiss it if needed
#Override
public void finish()
{
if (pd.isShowing()
{
pd.dismiss();
}
super.finish();
}
You could also Override onBackPressed() and put this code there but since pressing the back button calls finish() its probably safer just to do it there.
Also, you are comparing Strings correctly in one place
if (method.equals("POST")) // correct
but not others
else if (method == "GET") // incorrect

HttpPost and Thread Exception

Here is my code:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
MainActivity.this.runOnUiThread(new Runnable() {
public void run() {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(
"http://shopstable.turkcell.com.tr/timmenu/getPerosConfig.do");
try {
HttpResponse response = httpclient
.execute(httppost);
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
}
});
}
});
}
i'am getting NetworkOnMainThreadException. I think the problem is in the httppost, but i couldn't figure it out.
This exception is thrown when an application attempts to perform a networking operation on its main thread.This is only thrown for applications targeting the Honeycomb SDK or higher. Applications targeting earlier SDK versions are allowed to do networking on their main event loop threads, but it's heavily discouraged. Run your code in AsyncTask:
// use async task like this .this will solve ur problem
Class A{
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
MainActivity.this.runOnUiThread(new Runnable() {
public void run() {
new RequestLogInFromServer().execute();
}
});
}
});
}
public class RequestLogInFromServer extends AsyncTask<Object, Object, Object>
{
#Override
protected Object doInBackground(Object... params)
{
String responsearray[] = new String[2];
//JSONObject jsonResponse = null;
// Create a new HttpClient and Post Header
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://shopstable.turkcell.com.tr/timme/getPerosConfig.do");
httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
try {
// Add your data
in case if u want to pass any data to server else leave it
List<NameValuePair> signinDetails = new ArrayList<NameValuePair>();
signinDetails.add(new BasicNameValuePair("name",uname));
signinDetails.add(new BasicNameValuePair("pass",pwd));
httpPost.setEntity(new UrlEncodedFormEntity(signinDetails));
// Execute HTTP Post Request
HttpResponse httpResponse = httpClient.execute(httpPost);
Log.v("Post Status", "Code: "
+ httpResponse.getStatusLine().getStatusCode());
responseCode = httpResponse.getStatusLine().getStatusCode();
Log.e("responseBody", String.valueOf(responseCode));
responsearray[0]=String.valueOf(responseCode);
switch(responseCode){
case 200:
Log.e("responseCode", String.valueOf(responseCode));
HttpEntity entity = httpResponse.getEntity();
Log.e("entity", String.valueOf(entity));
if (entity != null) {
responsearray[1] = EntityUtils.toString(entity);
Log.e("responsearray", String.valueOf(responsearray));
/* Log.e("responseBody", String.valueOf(responseBody));
JSONTokener jsonTokener = new JSONTokener(responseBody);
jsonResponse = new JSONObject(jsonTokener);
Log.e("finalResult", String.valueOf(jsonResponse));
JSONObject response = jsonResponse.getJSONObject("response");
// Getting String inside response object
String status = response.getString("status");
String message = response.getString("message");
Log.e("status", String.valueOf(status));
Log.e("message", String.valueOf(message));
*/
} // if (entity != null) end
break;
case 503:
responsearray[1]="";
break;
default:
responsearray[1]="";
break;
}//switch end
} catch (ClientProtocolException cpeExp) {
// TODO Auto-generated catch block
} catch (Exception allExp) {
// TODO Auto-generated catch block
}
return responsearray;
}
#Override
protected void onPostExecute(Object result)
{
super.onPostExecute(result);
}
#Override
protected void onPreExecute() {
progressDialog = ProgressDialog.show(SignInActivity.this, "", "Please wait");
super.onPreExecute();
}
}
} //close class A
you have simply use this so get solution:
Here SDK version is your app's minimum sdk version ..so you have to set your minimum sdk version here. And put this code after onCreate() method:
if (android.os.Build.VERSION.SDK_INT > 8) {
StrictMode.ThreadPolicy stp = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(stp);
}
And also add this permission to your manifest file:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

Adding an AsyncTask - Android

I'm trying to add an AsyncTask to the following class but I'm not sure where to start. I would like to encapsulate the entire class if possible. I'm new to Android and Java so I really have no idea about what I'm doing. The following class works, and I can send all the information to my database properly. Each time the user's location is updated, the program first checks a table in the database for the user ID; if it does not exist in the table the GPS coordinates are sent, but if the user ID is in the table, the coordinates are not sent and the program stops sending location updates. This works like it should, but it locks up my UI and throws an ANR error when attempting to interact. I know that I need to implement an AsyncTask, but I need some guidance. Below is the complete code for the class. Any help would be great!
public class FindLocation {
protected static final Context SendLocation = null;
private LocationManager locManager;
private LocationListener locListener;
Context ctx;
public FindLocation(Context ctx) {
this.ctx = ctx;
}
public void startLocation(final Context context, String usr_id2) {
final String usr = usr_id2;
//get a reference to the LocationManager
locManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
//checked to receive updates from the position
locListener = new LocationListener() {
public void onLocationChanged(Location loc) {
String lat = String.valueOf(loc.getLatitude());
String lon = String.valueOf(loc.getLongitude());
JSONArray jArray;
String result = null;
InputStream is = null;
StringBuilder sb = null;
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("id", usr));
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.example.com/test/example.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection"+e.toString());
}
//convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
String line="0";
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result=sb.toString();
}
catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
try{
jArray = new JSONArray(result);
JSONObject json_data=null;
for(int i=0;i<jArray.length();i++){
json_data = jArray.getJSONObject(i);
String ct_name = json_data.getString("phoneID");
if(ct_name == usr) {
locManager.removeUpdates(locListener);
}
}
}
catch(Exception e){
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://example.com/test/example.php");
try {
List<NameValuePair> nameValuePairs1 = new ArrayList<NameValuePair>(2);
nameValuePairs1.add(new BasicNameValuePair("lat", lat));
nameValuePairs1.add(new BasicNameValuePair("lon", lon));
nameValuePairs1.add(new BasicNameValuePair("id", usr));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs1));
httpclient.execute(httppost);
}
catch (ClientProtocolException g) {
// TODO Auto-generated catch block
} catch (IOException f) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void onProviderDisabled(String provider){
}
public void onProviderEnabled(String provider){
}
public void onStatusChanged(String provider, int status, Bundle extras){
}
};
locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 6000, 0, locListener);
}
}
All you should have to do is:
modify FindLocation class by extending asynctask
change startLocation for an override of doInBackground.
Then call the execute method of your asynctask instead of startLocation.
Also, in your case, an asynctask may not be the best. Usually you use an asynctask because you want to do something in the background and then, when the task is done, update some ui components with the result of the background operation. Here, as you just want something in the background but no UI update, you could be better using a normal thread :
make you class extend thread
change startLocation for an override of run
start your thread instead of calling startLocation
--Update with details --
This could be simpler but the idea to get more familiar with asyncTask ia a good one too.
public class LocationFinder extends Thread {
public LocationFinder( Context ctx ) {
this.ctx = ctx;
}
public void start( String userId ) {
this.userId = userId;
super.start();
}
//defensive programming : prevent your thread from beeing started in an undesired way
#Override
public void start() {
throw new IllegalStateException( "LocationFinder can't be started using start(). Prefer start( int )." );
}
public void run() {
//remaining of the code of startLocation except the first line.
}
}
to use your thread then do in an activity :
new LocationFinder( this ).start( userId );
private class BackgroundLoader extends AsyncTask<Void, Void, Void> {
private ProgressDialog dialog;
protected Long doInBackground() {
dialog = new ProgressDialog(ctx);
dialog.show();
}
protected void doInBackground() {
// do all your stuff here that doesn't modify the UI
}
protected void onPostExecute(Long result) {
// do what you need to to the UI
dialog.dismiss();
}
Then to create an instance call new BackgroundLoader().execute(); in your onCreate() method

Categories

Resources