I am developing a login application using MySQL database. I am using JSONParser from the database package to connect to the local mysql database I am getting the following error please some one help me. I googled for this error but what I got is to use the AsyncTask but I don't know where to use and how to use and what is the Mainthread also.
Please some one edit my code and explain or post relevant codes...
"android.os.NetworkonMainThreadException" is the error when I running the application from 4.2 genymotion emulator...
package com.android.database;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url, List<NameValuePair> params) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
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();
Log.e("JSON", json);
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// 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());
}
// return JSON String
return jObj;
}
}``
Network Operations must be done in background.
You can use AsyncTask to accomplish this.
You are performing network operation on the UI thread and you can't do it. Consider using AsyncTask to do this kind operations, or an external library like this, which allows you to make Http request asynchronously in a very simple way.
I'm not sure if I understand your question correctly, and I would like to rather add a comment but am not allowed (too low rep) so here goes:
This class JSONParser i'm assuming is the "Activity" you are talking about. This is not an activity though, but a class, so you could rather create a new object of this class and use it from your calling activity:
JSONParser json = new JSONParser();
json.getJSONFromUrl(url,params);
Thing is, doing this parsing will take time and on the main UI thread this will probably pause the thread and might even let the app crash if the thread takes longer than 5 seconds to respond. This means you should use AsyncTask to run this JSONParser methods. A good place to start with learning AsyncTask is Vogella. He has some great tutorials on his site.
You will probably use doInBackground to run your getJSONFromUrl method and then update your UI thread from the onPostExecute method. So basically: Use AsyncTask
Related
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
I am asking this because I am beginner in android development.
I am doing a core-banking application, so I used JSON Parser class to connect with REST Web-Service,
JSONParser Class is,
package com.anvinsolutions.digicob_custmate;
import android.util.Log;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
public class JSONParser {
String charset = "UTF-8";
HttpURLConnection conn;
DataOutputStream wr;
StringBuilder result;// = new StringBuilder();
URL urlObj;
JSONObject jObj = null;
StringBuilder sbParams;
String paramsString;
public JSONObject makeHttpRequest(String url, String method,
HashMap<String, String> params) {
sbParams = new StringBuilder();
int i = 0;
for (String key : params.keySet()) {
try {
if (i != 0){
sbParams.append("&");
}
sbParams.append(key).append("=")
.append(URLEncoder.encode(params.get(key), charset));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
i++;
}
if (method.equals("POST")) {
// request method is POST
try {
urlObj = new URL(url);
conn = (HttpURLConnection) urlObj.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Accept-Charset", charset);
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.connect();
paramsString = sbParams.toString();
wr = new DataOutputStream(conn.getOutputStream());
wr.writeBytes(paramsString);
wr.flush();
wr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
else if(method.equals("GET")){
// request method is GET
if (sbParams.length() != 0) {
url += "?" + sbParams.toString();
}
try {
urlObj = new URL(url);
conn = (HttpURLConnection) urlObj.openConnection();
conn.setDoOutput(false);
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept-Charset", charset);
conn.setConnectTimeout(15000);
conn.connect();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
//Receive the response from the server
InputStream in = new BufferedInputStream(conn.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
result = new StringBuilder(); // add this line
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
Log.d("JSON Parser", "result: " + result.toString());
} catch (IOException e) {
e.printStackTrace();
}
conn.disconnect();
// try parse the string to a JSON object
try {
jObj = new JSONObject(result.toString());
} catch (Exception e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON Object
return jObj;
}
}
and i am confused if this method have any problem with Security,performance?
i didn't try any Libraries till now, i just used this JSONParaser Class. i think its easy to work with a JSONParser Class..
WHICH ONE TO USE?
thank you in advance! ;)
You never use JSonParser class to connect to a Web service. From your code, looks like you are using Vanilla HttpURLConnection class for connecting to service and using the JSonParser class to parse the result which is good and simple if you only have a couple of web requests to make in your application.
However since you said, it's banking application, you might have to think about scalability, multiple requests and stuffs like that. You could well try to handle them by yourself but the suggested way would be to use one of the tried and tested network libraries available for Android. Retrofit and Volley are two such and there are many more. The choice of the library to use is based on your use cases.
#AJay has already pointed to a page for comparison. Have a look.
Onto your next thing, about the parsing, performance is one of the key factors. Have a look at the below link for the options you have - http://blog.takipi.com/the-ultimate-json-library-json-simple-vs-gson-vs-jackson-vs-json/
I would say GSon is pretty good among all. We use it extensively in our in-house products.
You can use GsonParser by Google.https://github.com/google/gson
Hello you can use any of these 3 libraries they both are equally good in performance. Check this link, it will help you. Happy learning.
Comparison of Android networking libraries: OkHTTP, Retrofit, and Volley
If you have a deal with REST service, the easiest way is to use Retrofit library: https://square.github.io/retrofit/
With Retrofit you do not need to implement http calls and it automatically parses/creates json.
If you need more flexibility, I suggest using OkHttp library http://square.github.io/okhttp/, which is much simpler than pure HttpUrlConnection in combination with Gson lib https://github.com/google/gson for json parsing/creating.
I am new bee in Android , so the knowledge regarding android is not so vast.
I am trying to implement Json call in android and i am using the foolowing code to get the list of all the contacts in the database.
package com.example.library;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
public class SecondActivity extends Activity {
Button show_data;
JSONObject my_json_obj;
String path,firstname,lastname;
{
path = "http://192.168.71.129:3000/contacts";
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000);
HttpEntity entity;
HttpResponse response = null;
HttpURLConnection urlconn;
my_json_obj = new JSONObject();
}
}
I dont know if this is the right method but this code was already existing in another project and i have just made some change.
Please guide me through this one as i have gone through many stackoverflow and google answers,but it is very confusing as i am just a beginner and dont have knowledge of json calls in android.
I could give you a chunk of code and say "Hey try this", but like you stated that you are very new to Android so I simply wont.
I think its of more value that you can learn something beter by trying then simply copy pasting code(most of the time)
There are a couple of things you need to consider when you do network request and parsing data.
Network request you must always do this in a seperate thread then the UI thread, because if you dont youll get a NetworkOnMainUiThreadException if I am correct out the top of my head.
The same applies for parsing the data you have retrieved from your request.
I dont see any parsing of data in your current code but I just wanted to give you a headsup because you will prob do this at some point in your application.
Here you can find a tutorial how to do threading with the AsyncTask. this is "the way" how it should be done in Android, they realy made it easy for you.
When reading that tutorial you will get the basic knowlage to do stuff in this class.
When you get the concept of threading and how to work with this newly added skill I would suggest reading and following up on this json tutorial here.
I hope this helps
try this, result variable has your responce
try {
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet("paset_your_url_here");
HttpResponse response = client.execute(request);
BufferedReader in = new BufferedReader
(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
result = sb.toString();
Log.i("", "-----------------------"+result);
} catch(Exception e) {
e.printStackTrace();
}finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
if you want to prase json then first do googling and if you get your answer by this then vote up :)
I am trying to input text from Android into websites, and I read that httppost is a good option. I download the HttpClient 4.2.2 (GA) tar.gz, unzipped them, and copied the 7 jars into the lib folder of my android project in Eclipse. I'm pretty sure I got all the jars, since they matched those listed on the website.
I then proceeded to copy and paste the top tutorial from: http://hc.apache.org/httpcomponents-client-ga/quickstart.html
I imported everything, and was left with this error:
EntityUtils.consume(entity1); //X
} finally {
httpGet.releaseConnection(); //X
This portion of code is at two places in the tutorial, and errors occur at both.
Eclipse says for the first line:
"The method consume(HttpEntity) is undefined for the type EntityUtils."
Second line:
"The method releaseConnection() is undefined for the type HttpGet."
I'm pretty sure I downloaded every jar, transported them correctly, and imported everything. What is making the error? Thanks.
Here is what I have now. Edward, I used some of the code from your methods, but just put them into onCreate. However, this isn't working. A few seconds after I go from the previous activity to this one, I get the message that the app "has stopped unexpectedly".
I have a question about inputting my Strings into the website text fields: Do I use NameValuePairs of HttpParams? Here's my code, can you see what's wrong? Thanks.
package com.example.myapp;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.params.HttpClientParams;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.widget.Toast;
public class BalanceCheckerActivity extends Activity {
private final String LOGIN_URL = "https://someloginsite.com"; //username and password
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_balance_checker);
String username = getIntent().getExtras().getString("username");
String password = getIntent().getExtras().getString("password");
//Building post parameters, key and value pair
List<NameValuePair> accountInfo = new ArrayList<NameValuePair>(2);
accountInfo.add(new BasicNameValuePair("inputEnterpriseId", username));
accountInfo.add(new BasicNameValuePair("password", password));
//Creating HTTP client
HttpClient httpClient = new DefaultHttpClient();
//Creating HTTP Post
HttpPost httpPost = new HttpPost(LOGIN_URL);
BasicHttpParams params = new BasicHttpParams();
params.setParameter("inputEnterpriseID", username);
params.setParameter("password", password);
httpPost.setParams(params);
//Url Encoding the POST parameters
try {
httpPost.setEntity(new UrlEncodedFormEntity(accountInfo));
}
catch (UnsupportedEncodingException e) {
// writing error to Log
e.printStackTrace();
startActivity(new Intent(this, AccountInputActivity.class));
}
HttpResponse response = null;
InputStreamReader iSR = null;
String source = null;
// Making HTTP Request
try {
response = httpClient.execute(httpPost);
// writing response to log
Log.d("Http Response:", response.toString());
iSR = new InputStreamReader(response.getEntity().getContent());
BufferedReader br = new BufferedReader(iSR);
source = "";
while((source = br.readLine()) != null)
{
source += br.readLine();
}
} catch (ClientProtocolException e) {
// writing exception to log
e.printStackTrace();
startActivity(new Intent(this, AccountInputActivity.class));
} catch (IOException e) {
// writing exception to log
e.printStackTrace();
startActivity(new Intent(this, AccountInputActivity.class));
}
System.out.println(source);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_balance_checker, menu);
return true;
}
}
That mostly looks pretty good to me. I only saw one obviously wrong piece of code in it:
while((source = br.readLine()) != null)
{
source += br.readLine();
}
That's kind of a mess, and rather than try to untangle it, I'll just rewrite it.
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null)
sb.append(line);
String source = sb.toString();
Also, you shouldn't be doing network I/O from onCreate() or even from within your UI thread, since it can block for a long time, freezing your entire UI and possibly causing an "Application Not Responding" (ANR) crash. But for a simple test program, you can let that slide for now. For production code, you'd launch a thread or use AsyncTask().
Anyway, we're not really interested in building and debugging your program for you. Have you tried this code out? What was the result?
One final note: a login sequence like this is likely to return an authentication token in the form of a cookie. I forget how you extract cookies from an HttpResponse, but you'll want to do that, and then include any received cookies as part of any subsequent requests to that web site.
Original answer:
I think you've gotten yourself all tangled up. The Apache http client package is built into Android, so there's no need to download any jar files from apache.
I'm not familiar with EntityUtils, but whatever it is, if you can avoid using it, I would do so. Try to stick with the bundled API whenever possible; every third-party or utility library you add to your application increases bloat, and on mobile devices, you want to keep your application as light as possible. As for the actual "consume()" method not being found, that's probably a mistake in the documentation. They probably meant consumeContent().
The releaseConnection() call is probably only necessary for persistent connection. That's relatively advanced usage; I don't even do persistent or managed connections in my own code.
You haven't provided enough information to let us know what it is you're trying to do, but I'll try give you a reasonably generic answer.
There are many, many ways to transmit data to a server over the http protocol, but in the vast majority of cases you want to transmit form-encoded data via HttpPost.
The procedure is:
Create a DefaultHttpClient
Create an HttpPost request
Add headers as needed with setHeader() or addHeader().
Add the data to be transmitted in the form of an HttpEntity
Call client.execute() with the post request
Wait for and receive an HttpResponse; examine it for status code.
If you're expecting data back from the server, use response.getEntity()
There are many HttpEntity classes, which collect their data and transmit it to the server each in their own way. Assuming you're transmitting form-encoded data, then UrlEncodedFormEntity is the one you want. This entity takes a list of NameValuePair objects which it formats properly for form-encoded data and transmits it.
Here is some code I've written to do this; these are only code fragments so I'll leave it to you to incorporate them into your application and debug them yourself.
/**
* POST the given url, providing the given list of NameValuePairs
* #param url destination url
* #param data data, as a list of name/value pairs
*/
public HttpResponse post(String url, List<NameValuePair> data) {
HttpPost req = new HttpPost(url);
UrlEncodedFormEntity e;
try {
e = new UrlEncodedFormEntity(data, "UTF-8");
} catch (UnsupportedEncodingException e1) {
Log.e(TAG, "Unknown exception: " + e1);
return null; // Or throw an exception, it's up to you
}
return post(req, e);
}
/**
* Post an arbitrary entity.
* #param req HttpPost
* #param data Any HttpEntity subclass
* #return HttpResponse from server
*/
public HttpResponse post(HttpPost req, HttpEntity data) {
try {
HttpClient client = new DefaultHttpClient();
req.setEntity(data);
HttpResponse resp = client.execute(req);
int status = resp.getStatusLine().getStatusCode();
if (status != HttpStatus.SC_OK) {
Log.w(TAG,
"http error: " + resp.getStatusLine().getReasonPhrase());
return null; // Or throw an exception, it's up to you
}
return resp;
} catch (ClientProtocolException e) {
Log.e(TAG, "Protocol exception: " + e);
return null;
} catch (UnknownHostException e) {
return null;
} catch (IOException e) {
Log.e(TAG, "IO exception: " + e);
return null;
} catch (Exception e) {
// Catch-all
Log.e(TAG, "Unknown exception: " + e);
return null;
}
}
I have the following code which takes a normal HTTP GET Request and returns the output html as a string.
public static String getURLContent(String URL){
String Result = "";
String IP = "http://localhost/";
try {
// Create a URL for the desired page
URL url = new URL(IP.concat(URL));
// Read all the text returned by the server
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String str;
while ((str = in.readLine()) != null) {
// str is one line of text; readLine() strips the newline character(s)
Result = Result+str+"~";
}
in.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return Result;
}
I would like to implement the same sort of thing for an unsigned ssl certificate but I am a bit of a novice at Java or Android programming and find some previous responses to similar questions very confusing.
Could someone change the code above to work with HTTPS requests?
One other question, would there be a risk of a middle-man-attack if I sent unencrypyted data via the GET request and print out database entries onto the webpage that the function returns the content of. Would it be better to use a POST request?
The reason I chose to use SSL is because someone told me that the data sent is encrypted. The data is sensitive and if I send something like localhost/login.php?user=jim&password=sd7vbsksd8 which would return "user=jim permission=admin age=23" which is data that I don't want others to see if they simply used a browser and sent the same request.
Try this:
import java.io.IOException;
import java.io.InputStreamReader;
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;
public class TestHttpGet {
public void executeHttpGet() throws Exception {
BufferedReader in = null;
try {
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI("http://w3mentor.com/"));
HttpResponse response = client.execute(request);
in = new BufferedReader
(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
String page = sb.toString();
System.out.println(page);
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
We can add parameters to an HTTP Get request as
HttpGet method = new HttpGet("http://w3mentor.com/download.aspx?key=valueGoesHere");
client.execute(method);
Android should automatically work with ssl. Maybe ssl certificate you are using on localhost is not trusted? Check this: Trusting all certificates using HttpClient over HTTPS
Check if you are able to browse https://yourhost/login.php?user=jim&password=sd7vbsksd8 using your browser.
hy,
I'd like to insert a person into the database, so I have to post the name and firstname
here is json url http://localhost:8075/myproject/personne/new
I thought to use
Map map = new HashMap ();
map.put ("name", "aaaaa");
map.put ("firstname", "eee");
but , I do not know WHAT TO DO to post the variables in the server.
you have to create a server side page, for example insert.php.
Then make httppost from your android application to server side page("insert.php")
here is an example about connect to remote database in android
I'm assuming you already have your server up and running (so it's already accepting and handling post requests). Please also use an IDE that manages the imports automatically, I just added them for reference.
Following code is copy/paste from one of my projects and untested (please also excuse invalid references I might have missed).
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
private Response execute(String jsonData) {
String url = "http://localhost:8075/myproject/personne/new";
HttpPost post = new HttpPost(url);
ArrayList<NameValuePair> parameters = new ArrayList<NameValuePair>();
parameters.add(new BasicNameValuePair("data", jsonData));
try {
post.setEntity(new UrlEncodedFormEntity(parameters));
HttpClient httpClient = new DefaultHttpClient();
HttpResponse response = httpClient.execute(post);
return parseResponse(response);
} catch (UnsupportedEncodingException e) {
Log.e(TAG, "Unsupported encoding in JSON data", e);
} catch (ClientProtocolException e) {
Log.e(TAG, "Protocol based error", e);
} catch (IOException e) {
Log.e(TAG, "IO Exception", e);
}
return null;
}
private Response pushPerson(Person person) {
try {
JSONObject json = new JSONObject();
json.put("firstname", person.firstname);
json.put("lastname", person.lastname);;
return execute(json.toString());
} catch (JSONException e) {
Log.e(TAG, "Error pushing person", e);
}
return null;
}
As you can see there's no need for a HashMap, the JSONObject is what you are looking for. The Response can be nearly anything, that's up to you. "Normally" you would return the id of the newly created person.
There are plenty of tutorials out there. When I started I found each of them just by using a search engine. Please also always take a look at the Android docs.