Unable to get the response from JSON - java

I am new to android. Well what I am trying to do in the following code is making an http request sending to a php file from where json gets the response. In the php file I am trying to show the city names starting from A. Whenever I am running the code I am getting this error: "org.json.jsonexception value doctype of type java.lang.string cannot be converted to jsonarray". All The related Threads are of no help or i am not able to understand the solution given there.
Here is my Java Code
MainActivity.java
package com.list;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
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.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.net.ParseException;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
JSONArray jArray;
String result = null;
InputStream is = null;
StringBuilder sb=null;
int ct_id;
String ct_name;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView textview1 = (TextView)findViewById(R.id.textView1);
textview1.setText("Erqem");
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://10.0.2.2/city.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,"UTF-8"),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
try{
jArray = new JSONArray(result);
JSONObject json_data = new JSONObject();
json_data=null;
for(int i=0;i<jArray.length();i++){
json_data = jArray.getJSONObject(i);
ct_id=json_data.getInt("CITY_ID");
ct_name=json_data.getString("CITY_NAME");
textview1.setText(ct_name);
}
}
catch(JSONException e1){
Toast.makeText(getBaseContext(), "No City Found"+e1.toString() ,Toast.LENGTH_LONG).show();
Log.e("log_tag", "Error converting result "+e1.getMessage() );
} catch (ParseException e1) {
e1.printStackTrace();
}
}
}
php file
<?php
header('Content-type=application/json; charset=utf-8');
mysql_connect("","root","");
mysql_select_db("Deal");
$sql=mysql_query("select * from CITY where CITY_NAME like 'A%'");
while($row=mysql_fetch_assoc($sql))
$output[]=$row;
print(json_encode($output));
mysql_close();
?>
Any Help would be appreciated.Thanks.

maybe you are using incorrect address, please try 10.0.2.2:8080/city.php

Related

Error when connecting to online database

I am trying to connect to an external database on my server via AsyncTask but Eclipse is showing me an error in the log-
See the error image.
Here is the code I am using-
MainActivity.java:
package com.deltware.newco;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
TextView res;
Button btn1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.res = (TextView) this.findViewById(R.id.textView1);
this.btn1 = (Button) this.findViewById(R.id.button1);
this.btn1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
new getAllUsersTask().execute(new Connector());
}
});
}
public void setTextToView(JSONArray json){
String s= "";
for(int i = 0; i<json.length(); i++){
JSONObject jo = null;
try{
jo = json.getJSONObject(i);
s += "Name: " + jo.getString("name") +
"Email: " + jo.getString("email");
}catch(JSONException e){
e.printStackTrace();
}
}
this.res.setText(s);
}
private class getAllUsersTask extends AsyncTask<Connector, Long,JSONArray>{
#Override
protected JSONArray doInBackground(Connector... param) {
return param[0].getAllUsers();
}
#Override
protected void onPostExecute(JSONArray result) {
setTextToView(result);
}
}
}
Connector.java:
package com.deltware.newco;
import java.io.IOException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.DefaultClientConnection;
import org.apache.http.protocol.DefaultedHttpContext;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import android.util.Log;
public class Connector {
public JSONArray getAllUsers(){
String url = "url to the location of my php file";
HttpEntity httpEntity = null;
try{
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpget);
httpEntity = httpResponse.getEntity();
}catch(ClientProtocolException e){
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
JSONArray json = null;
if(httpEntity == null){
try{
String entityResponse = EntityUtils.toString(httpEntity);
Log.e("Entity Response:",entityResponse);
json = new JSONArray(entityResponse);
}catch(JSONException e){
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
}
return json;
}
}
PHP file:
$query = mysqli_query($db, "SELECT name, email, gender FROM users");
while($row = mysqli_fetch_assoc($query)){
$ouput[] = $row;
}
echo json_encode($ouput);
I am using Eclipse and Android 4.4 KitKat.

How to make a "raw" string out of JSON in Java

I am coding an android app for school atm. i am stock and want to ask you guy to help me.
So far i understand how to use PHP to print data from a MySQL database ready to be parset in Java. Then my code(taken from here: http://www.helloandroid.com/tutorials/connecting-mysql-database)takes the data and converts it into strings i believe.
So my question is: how do i for eksample make and if statement to check if the userdata is correct? i just dont get it!
Here is all my code for the activity(login form) i use:
package com.example.fungi;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
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;
import android.app.ActionBar;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
//Intent i = new Intent(getBaseContext(), MainPageActivity.class);
//startActivity(i);
Button login;
EditText username;
EditText password;
TextView lol;
JSONArray jArray;
String result = null;
InputStream is = null;
StringBuilder sb=null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//ActionBar actionBar = getActionBar();
//actionBar.hide();
lol = (TextView) findViewById(R.id.textView1);
login = (Button) findViewById(R.id.loginbutton);
username = (EditText) findViewById(R.id.usernametext);
password = (EditText) findViewById(R.id.passwordtext);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String usernameget = username.getText().toString();
String passwordget = password.getText().toString();
if(usernameget.contentEquals("")){
username.setText("usernam required");
}else {
if(passwordget.contentEquals("")){
username.setText("password required");
}else {
String userid = username.getText().toString();
Intent intent = new Intent(getBaseContext(), Side.class);
intent.putExtra("sessionid", userid);
startActivity(intent);
}
}
}
});
String result = "";
//the year data to send
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair(result, result));
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://http://fungi.webatu.com/Index.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent();
}catch(Exception e11){
Log.e("log_tag", "Fejl i HTTP connection "+e11.toString());
}
//convert response to string
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();
result=sb.toString();
}catch(Exception e){
Log.e("log_tag", "Fejl i resultat konvertering "+e.toString());
}
//parse json data
try{
JSONArray jArray = new JSONArray(result);
for(int i=0;i<jArray.length();i++){
JSONObject json_data = jArray.getJSONObject(i);
Log.i("log_tag","id: "+json_data.getInt("id")+
", username: "+json_data.getString("username")+
", password: "+json_data.getString("password")+
", alder: "+json_data.getInt("alder"));
//maybe if statement here?
;
}
}
catch(JSONException e1){
Log.e("log_tag", "Error parsing data "+e1.toString());
}
}
}
thanks in advance!!
I'm not sure about your issue, but I think you want to get some JSON data from a webservice.
Developing to Android, you cannot use network resources on the main thread. So you will need to start a new thread. To reach that, you can use AsyncTask or use the Thread class.
public static JSONArray getJSONArrayFromURL(String url) {
// initialize
InputStream is = null;
String result = "";
JSONArray jArray = null;
Log.d("URL_SEARCH", url);
// http post
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
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 = null;
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 parse the string to a JSON object
try {
jArray = new JSONArray(result);
Log.d("URL_SEARCH", "JSON: " + jArray.length());
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
return jArray;
}

Android php+mysql+json error implementing AsyncTask

Im new to Android and I need a little help. I have a class witch values from one table located on remote mysql and its working fine on 2.3 but on 4.x Im getting errors when I start it. I have read somewhere its because I`m not using AsyncTask. I tried to implement it on existing working code but there is one error, so please help because I tried everything to get this to work but no success.
Here is the existing code that works on 2.3
package com.stole.fetchtest;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
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.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
import android.net.ParseException;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.Toast;
public class FetchData extends ListActivity {
#SuppressWarnings("unchecked")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String result = null;
InputStream is = null;
StringBuilder sb = null;
ArrayList<?> nameValuePairs = new ArrayList<Object>();
List<String> r = new ArrayList<String>();
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(
"http://www.url.com/fetch.php");
httppost.setEntity(new UrlEncodedFormEntity(
(List<? extends NameValuePair>) nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.toString(), Toast.LENGTH_LONG)
.show();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "UTF-8"));
sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.toString(), Toast.LENGTH_LONG)
.show();
}
try {
JSONArray jArray = new JSONArray(result);
JSONObject json_data = null;
for (int i = 0; i < jArray.length(); i++) {
json_data = jArray.getJSONObject(i);
r.add(json_data.getString("names"));
}
setListAdapter(new ArrayAdapter<String>(this, R.layout.names_row, r));
} catch (JSONException e1) {
Toast.makeText(getBaseContext(), e1.toString(), Toast.LENGTH_LONG)
.show();
} catch (ParseException e1) {
Toast.makeText(getBaseContext(), e1.toString(), Toast.LENGTH_LONG)
.show();
}
}}
And then I tried to add AsyncTask, according to some tutorials found online, and it`s looking like this:
package com.stole.fetchtest;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
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.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
import android.net.ParseException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.Toast;
public class FetchData extends ListActivity {
String result = null;
InputStream is = null;
StringBuilder sb = null;
ArrayList<?> nameValuePairs = new ArrayList<Object>();
List<String> r = new ArrayList<String>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
new task().execute();
}
public class task extends AsyncTask<String, String, Void> {
#SuppressWarnings("unchecked")
#Override
protected Void doInBackground(String... params) {
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.url.com/fetch.php");
httppost.setEntity(new UrlEncodedFormEntity(
(List<? extends NameValuePair>) nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.toString(),
Toast.LENGTH_LONG).show();
}
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(is, "iso-8859-1"));
sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.toString(),
Toast.LENGTH_LONG).show();
}
return null;
}
protected void onPostExecute(Void v) {
try {
JSONArray jArray = new JSONArray(result);
JSONObject json_data = null;
for (int i = 0; i < jArray.length(); i++) {
json_data = jArray.getJSONObject(i);
r.add(json_data.getString("naziv"));
}
setListAdapter(new ArrayAdapter(this, R.layout.names_row, r));
} catch (JSONException e1) {
Toast.makeText(getBaseContext(), e1.toString(),
Toast.LENGTH_LONG).show();
} catch (ParseException e1) {
Toast.makeText(getBaseContext(), e1.toString(),
Toast.LENGTH_LONG).show();
}
}
}
}
The error I`m getting is at
setListAdapter(new ArrayAdapter(this, R.layout.names_row, r));
and it says "The constructor ArrayAdapter(FetchData.task, int, List) is undefined"
Thanks!
it should use the activity context not the task context..
setListAdapter(new ArrayAdapter(FetchData.this, R.layout.names_row, r));

Create json object in servlet

I want to send retrieved data from sever to my Android client... I used a json object to do that. Here is my servlet code.
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
public class AvailabilityResponse extends HttpServlet {
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("application/json");
PrintWriter out=response.getWriter();
String br_id;
br_id=request.getParameter("branchname");
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:8888/atmlivedetails","root","root");
Statement st=con.createStatement();
ResultSet rs=st.executeQuery("select atmbrno, atmbrname from location_stat where act_brname='"+br_id+"'");
while(rs.next()){
String s = rs.getString("atmbrno");
String t = rs.getString("atmbrname");
JSONObject arrayObj = new JSONObject();
arrayObj.put("atmbrno",s);
arrayObj.put("atmbrname",t);
out.print(arrayObj);
}
rs.close ();
st.close ();
}
catch(Exception e){
out.print(e);
}
}
}
And This is my android side code..
import java.util.ArrayList;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.ClientProtocolException;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import android.os.Bundle;
public class CheckAvailability extends Activity{
Button but1,but2;
EditText brName;
TextView txt1;
String text;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.availability);
brName =(EditText)findViewById(R.id.editText1);
but1 = (Button)findViewById(R.id.button5);
but2 = (Button)findViewById(R.id.button6);
txt1 = (TextView)findViewById(R.id.textView3);
but1.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
String result = null;
InputStream is = null;
StringBuilder sb=null;
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("branchname", brName.getText().toString()));
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://10.0.2.2:8080/hello/AvailabilityResponse");
httppost.setEntity(new UrlEncodedFormEntity(postParameters));
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
String atm_id;
String atm_name;
try{
JSONArray jArray = new JSONArray(result);
JSONObject json_data=null;
for(int i=0;i<jArray.length();i++){
json_data = jArray.getJSONObject(i);
atm_id=json_data.getString("atmbrno");
atm_name=json_data.getString("atmbrname");
//txt1.setText(atm_name);
}
}catch(JSONException e1){
Toast.makeText(getBaseContext(), "No DATA Found", Toast.LENGTH_LONG).show();
}catch (ParseException e1){
e1.printStackTrace();
}
}
});
}
}
but when i run it it always gives me "No DATA Found" Exception...can any one help me???
Your servlet returns only N number of JSON objects. But your giving that response to JSON array it may be the mistake try this code in your servlet
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:8888/atmlivedetails","root","root");
Statement st=con.createStatement();
ResultSet rs=st.executeQuery("select atmbrno, atmbrname from location_stat where act_brname='"+br_id+"'");
int i=0;
JSONArray jArray = new JSONArray();
while(rs.next()){
String s = rs.getString("atmbrno");
String t = rs.getString("atmbrname");
JSONObject arrayObj = new JSONObject();
arrayObj.put("atmbrno",s);
arrayObj.put("atmbrname",t);
jArray.add(i,arrayObj);
i++;
}
rs.close ();
st.close ();
out.print(jArray);
}
print the response from server, before processing json string(converting to json object) so that you can track actual reason. U are getting json exception actually.
After writing to the outputstream, you need to close the Printwriter obejct like this.
out.close()
You need to add json-lib-2.4-jdk15.jar file to your project class-path and use following code to create JSON object.
JSONObject jsonData = new JSONObject();
jsonData.put("key1", "value1");
jsonData.put("key2", "value2");
jsonData.put("key3", "value3");
System.out.println("JSON data: "+jsonData.toString());
Console you will get output: JSON data: {"key1":"value1","key2":"value2","key3":"value3"}

Android connecting to MySql (PHP Script)

My java code:
package com.Cmode.ThesisSystem;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
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.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
import android.net.ParseException;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
public class EventLogs extends ListActivity {
JSONArray jArray;
String result = null;
InputStream is = null;
StringBuilder sb=null;
int e_id;
String e_name;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();{
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.my.com/eventlogs.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());
}
//paring data
try{
jArray = new JSONArray(result);
JSONObject json_data=null;
for(int i=0;i<jArray.length();i++){
json_data = jArray.getJSONObject(i);
e_id=json_data.getInt("id");
e_name=json_data.getString("event");
}
}catch(JSONException e1){
Toast.makeText(getBaseContext(), "No events found" ,Toast.LENGTH_LONG).show();
} catch (ParseException e1) {
e1.printStackTrace();
}
}
}
}
I have a problem with this code
Error:
The application CDroidMonitoring(process.com.Cmode.ThesisSystem) has stopped unexpectedly. Please try again
Im just new to android development. I think I have put something unusable braces or there is something wrong in the code.
Does your application have the INTERNET permission set in the manifest?
And for more information about the error check the logcat tab in Eclipse, it usually has a more descriptive error message.

Categories