The following Code is not able to connect to SQLite.
public class MainActivity extends ListActivity {
JSONArray jArray; String result = null; InputStream is = null;
StringBuilder sb=null;
#Override public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayList<NameValuePair> nameValuePairs = new
ArrayList<NameValuePair>(); //http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://xxx.xxx.xxx.xxx/");
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());
} //paring data
int Ravid_id;
String Ravid_Name;
try{
jArray = new JSONArray(result);
JSONObject json_data=null;
for(int i=0;i<jArray.length();i++){
json_data = jArray.getJSONObject(i);
Ravid_id=json_data.getInt("Ravid_id");
Ravid_Name=json_data.getString("Ravid_Name");
}
} catch(JSONException e1){
Toast.makeText(getBaseContext(), "No found" ,Toast.LENGTH_LONG).show();
} catch (ParseException e1) {
e1.printStackTrace();
}
}
}
This is just a guess and related to an often posted issue: you should not perform any network operations on the main thread. This code ...
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://xxx.xxx.xxx.xxx/");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
... should be in placed in an AsncTask or Service. See this post for an example how to fix this issue (usually an android.os.NetworkOnMainThreadException).
Related
Hey guys im trying to insert some data into a database from an android app, but the app crashes when trying to do so, i have the error log, but cant quite seem to figure out what it does. Can anyone please help me?
This is the error log: https://pastebin.com/Z8HmE21T
This is the code: https://pastebin.com/pCWaFniC
And this is my json parser
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if(method == "POST"){
// request method is POST
// 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();
}else if(method == "GET"){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "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());
}
// 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;
public class HttpPosrHitter {
public static String getJSONfromURL(String url, String member_id,
String phonenumber) {
InputStream is = null;
String result = "";
JSONObject jArray = null;
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("memberid", member_id));
pairs.add(new BasicNameValuePair("numbers", phonenumber));
httppost.setEntity(new UrlEncodedFormEntity(pairs));
// http post
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, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = "";
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 JSONObject(result);
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
return result;
}
}
This is class from which i am Post Phone Number to web service and getting response .
when i Post Number of Phone which has 15 to 20 contact i am getting response . but when i post number which has 150 contact i am not getting response one at a time i have to relaunch app two time then i am getting response . i dont know where i am doing mistake . even i am unable to read phone large file in chunks with fixed size buffer.
Just to solve all your potential bugs in one single shot: is there anything preventing you from using Retrofit and GSON or Jackson?
Each time I see such JSON/InputStream/URLConnection/... questions, I keep wondering why people keep on spending time to reinvent basic stuff instead of actually writing apps.
public class HttpPosrHitter {
public static String getJSONfromURL(String url, String member_id,
String phonenumber) {
InputStream is = null;
String result = "";
JSONObject jArray = null;
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("memberid", member_id));
pairs.add(new BasicNameValuePair("numbers", phonenumber));
httppost.setEntity(new UrlEncodedFormEntity(pairs));
// http post
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
result = EntityUtils.toString(entity); //changes Made
} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
}
try {
jArray = new JSONObject(result);
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
return result;
}
}
I am currently learning to develop android application. I need to parse variables from my android application to the servlet. I use HttpResponse to parse the variables. But i do not know how to accept parameters in servlet.
This is my code in android application.
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://<ip_address>:8080/GetPhoneNumber/GetPhoneNumberServletServlet");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("phoneNum", "12345678"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} // End of onClick method
May I know what to do at the doPost/doGet in servlet?
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
PrintWriter out = response.getWriter();
out.println("Hello Android !!!!");
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
In your doPost use request.getParameter("phoneNum").
I think the following code could help you.
public class CustomHttpClient
{
public static final int HTTP_TIMEOUT = 30 * 1000;
private static HttpClient mHttpClient;
private static HttpClient getHttpClient()
{
if (mHttpClient == null)
{
mHttpClient = new DefaultHttpClient();
final HttpParams params = mHttpClient.getParams();
HttpConnectionParams.setConnectionTimeout(params, HTTP_TIMEOUT);
HttpConnectionParams.setSoTimeout(params, HTTP_TIMEOUT);
ConnManagerParams.setTimeout(params, HTTP_TIMEOUT);
}
return mHttpClient;
}
public static String executeHttpPost(String url,ArrayList<NameValuePair> postParameters) throws Exception
{
BufferedReader in = null;
try
{
HttpClient client = getHttpClient();
HttpPost request = new HttpPost(url);
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters);
request.setEntity(formEntity);
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 result = sb.toString();
return result;
}
finally
{
if (in != null)
{
try
{
in.close();
}
catch (IOException e)
{
Log.e("log_tag", "Error converting result "+e.toString());
e.printStackTrace();
}
}
}
}
public static String executeHttpGet(String url) throws Exception
{
BufferedReader in = null;
try
{
HttpClient client = getHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI(url));
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 result = sb.toString();
return result;
}
finally
{
if (in != null)
{
try
{
in.close();
}
catch (IOException e)
{
Log.e("log_tag", "Error converting result "+e.toString());
e.printStackTrace();
}
}
}
}
}
Addons:-
Use the JSON Parser class below:-
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if(method == "POST"){
// request method is POST
// 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();
}else if(method == "GET"){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "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();
Log.d("json data",json.toString());
} 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;
}
}
Now if you want to send anything on the server, say you need to save the username and password on the server using the JSON Parser and PHP use the below code in any thread or in the doInBackground method of Async task.
ArrayList<NameValuePair> Insert = new ArrayList<NameValuePair>();
Insert.add(new BasicNameValuePair("User_Name","<Sting denoting username>"));
Insert.add(new BasicNameValuePair("Password","<Sting denoting Password>));
try
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://server path/yourphpfile.php");
httppost.setEntity(new UrlEncodedFormEntity(Insert));
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());
}
Now if you need these values back using the get method in JSON Parser, user the following code again in the Thread or doInBackground method of Async task.
public class CountDownTask extends AsyncTask<Void,Void , Void>
{
protected void onPreExecute()
{
count = 0;
S_Store_Id = null; S_Store_Name = null;S_Store_Address = null; S_Store_Phone= null;
Offers = null; Descriptions = null;
}
protected Void doInBackground(Void... params)
{
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("User_Name",StringUserName));
String response = null;
try
{
response = CustomHttpClient.executeHttpPost("http://yourserverpath/yourphpfilefor retrivingdata.php",postParameters);
String result = response.toString();
try
{
JSONArray jArray = new JSONArray(result);
JSONObject json_data = jArray.getJSONObject(0);
StringUserName = json_data.getString("User_Name");
StringPassword = json_data.getString("Password");
json_data = jArray.getJSONObject(1);
}
catch(JSONException e)
{
Log.e("log_tag", "Error parsing data "+e.toString());
}
}
catch (Exception e)
{
Log.e("log_tag","Error in http connection!!" + e.toString());
}
return null;
}
Now you can write the logic for inserting and retriving data from the server in your corresponding PHP files and use them for using data from the server. This method works equivalent to HTTP Get and Post methods of HTTP Request and Response.
Hope it can help you.. Thanks...
I am using this code to POST and GET data from MySQL database .
However when getting data that is not in English, it is displayed as question marks ?
what changes do I make to enable Hebrew language use ?
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
public JSONParser() {
}
public JSONObject makeHttpRequest(String url, String method,List<NameValuePair> params) {
try {
if(method == "POST"){
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();
}else if(method == "GET"){
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "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());
}
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
return jObj;
}
}
Make sure your HTTP response comes out encoded in Unicode (UTF-8 for example), and also your client (the application consuming the service) must be aware that of that encoding to read your response.
I am trying to get the USD average price 30d for bitcoins from here: http://api.bitcoincharts.com/v1/weighted_prices.json. The Json code I have does not work in the try/catch, and the error is a null (I have tried looking into other questions but all of them seem to return errors, whereas mine just returns a null):
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dogewidget);
TextView btctest = (TextView) findViewById(R.id.title);
//Create a new HTTP Client
DefaultHttpClient httpclient = new DefaultHttpClient();
//Setup the get request
HttpPost httppost = new HttpPost("http://api.bitcoincharts.com/v1/weighted_prices.json");
//Depending on web service
httppost.setHeader("Content-type", "application/json");
InputStream inputStream = null;
String result = null;
try {
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
result = reader.readLine();
JSONObject jObject = new JSONObject(result);
JSONObject jsubObject = jObject.getJSONObject("USD");
String btcjson = jsubObject.getString("30d");
btctest.setText(btcjson);
} catch (Exception e) {
e.printStackTrace();
Log.e("error", "" + e.getMessage());
btctest.setText("Error " + e.getMessage());
} finally {
try {
if (inputStream != null) inputStream.close();
} catch (Exception squish) {
}
}
}
}
Any help would be appreciated! Thanks.
Try this code.
private void get_value(String php) {
String responseString = null;
try{
HttpClient httpclient = new DefaultHttpClient();
String url ="your_url";
HttpPost httppost = new HttpPost(url);
HttpResponse response = httpclient.execute(httppost);
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
responseString = out.toString();
Toast.makeText(getApplicationContext(),responseString,1000).show();
//The below code is for Separating values.It may varies according with your result
JSONArray ja = new JSONArray(responseString);
int x=Integer.parseInt(ja.getJSONObject(0).getString("your_string_name"));
} catch(Exception e) {
}
}