org.json.JSONException no charge data - android

I have this problem on call data from mysql bd to android app, this is the mainactivity
public class CargaPrincipal extends ActionBarActivity {
ListView listaJSON;
//ArrayList<Empresa> empresaAvaiable = new ArrayList<Empresa>();
//Empresa emp;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home);
listaJSON = (ListView) findViewById(R.id.lv_empresas);
//ArrayList<empresa> empresaAvaiable = new ArrayList<empresa>();
Tarea1 tarea1 = new Tarea1();
tarea1.cargarContenido(getApplicationContext());
//tarea1.onPreExecute();
tarea1.execute(listaJSON);
}
static class Tarea1 extends AsyncTask<ListView, Void, ArrayAdapter<Empresa>>{
Context contexto;
ListView list;
InputStream is;
ArrayList<Empresa> listaempresas = new ArrayList<Empresa>();
public void cargarContenido(Context contexto){
this.contexto = contexto;
}
#Override
public void onPreExecute(){
//vacio
}
#Override
protected ArrayAdapter<Empresa> doInBackground(ListView... params){
list = params[0];
String resultado = "fallo";
Empresa emp;
HttpClient cliente = new DefaultHttpClient();
HttpGet peticionGet = new HttpGet("http://xxxxxxxx/xxxx/xxxxxxxx.php");
try {
HttpResponse response = cliente.execute(peticionGet);
HttpEntity contenido = response.getEntity();
is = contenido.getContent();
} catch (ClientProtocolException e) {
// TODO: handle exception
e.printStackTrace();
} catch (IOException e){
e.printStackTrace();
}
BufferedReader buferlector = null;
try {
buferlector = new BufferedReader(new InputStreamReader(is, HTTP.UTF_8), 8);
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
StringBuilder sb = new StringBuilder();
String linea = null;
try {
while((linea = buferlector.readLine()) != null ){
sb.append(linea);
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
try {
is.close();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
resultado = sb.toString();
try {
JSONArray arrayJson = new JSONArray(resultado);
for(int i = 0; i < arrayJson.length(); i++){
JSONObject objetoJson = arrayJson.getJSONObject(i);
emp = new Empresa(objetoJson.getInt("id_empresa"), objetoJson.getString("desc_empresa"));
//emp.setData(objetoJson.getString("img_empresa"));
listaempresas.add(emp);
}
} catch (JSONException e) {
// TODO: handle exception
e.printStackTrace();
}
ArrayAdapter<Empresa> adaptador = new ArrayAdapter<Empresa>(contexto, android.R.layout.simple_list_item_1, listaempresas);
return adaptador;
}
#Override
protected void onPostExecute(ArrayAdapter<Empresa> result){
list.setAdapter(result);
}
#Override
protected void onProgressUpdate(Void... values){
//vacio
}
}
this is the log cat ;
org.json.JSONException: Value <pre>!DOCTYPE of type java.lang.String cannot be converted to JSONArray</pre>
org.json.JSON.typeMismatch(JSON.java:111)
org.json.JSONArray.<init>(JSONArray.java:91)
org.json.JSONArray.<init>(JSONArray.java:103) com.siont.divi.CargaPrincipal$Tarea1.doInBackground(CargaPrincipal.java:120)
com.siont.divi.CargaPrincipal$Tarea1.doInBackground(CargaPrincipal.java:1)
android.os.AsyncTask$2.call(AsyncTask.java:287)
java.util.concurrent.FutureTask.run(FutureTask.java:234)
android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
java.lang.Thread.run(Thread.java:856)
i dont realize whats the problem, i give permissions on server

As LogCat show, it seems that the resultado variable contains wrong text, instead of Json Array format, witch has to be in this way "[ ..... ] ". Try to verify this variable before conversion.

Related

How to parse data from multiple URLs using asyncTask

The main problem is I'm unable to return two value help. i have tried lot of time but no success. And guys I'm new to this so please write your answer with respect to my code thanks in advance.
Here's my code
public class calculate extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
try {
uss = getJson("http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.xchange%20where%20pair%20in%20(%22INRUSD%22)&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=");
JSONObject usjObj;
usjObj = new JSONObject(uss);
usResult = usjObj.getJSONObject("query").getJSONObject("results").getJSONObject("rate").getString("Rate");
eurr = getJson("http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.xchange%20where%20pair%20in%20(%22INREUR%22)&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=");
JSONObject eurjObj;
eurjObj = new JSONObject(eurr);
eurResult = eurjObj.getJSONObject("query").getJSONObject("results").getJSONObject("rate").getString("Rate");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return eurResult + usResult;
////PROBLEM IS HERE ACTUALLY I DON'T KNOW HOW TO RETURN TWO OR MORE VALUE/////"
}
#Override
protected void onPostExecute(String usResult) {
valueus = Double.parseDouble(usResult);
inputus = lengthvalue * valueus;
us.setText("" + inputus);
valueeur = Double.parseDouble(eurResult);
inputeur = lengthvalue * valueeur;
eur.setText("" + inputeur);
}
}
public String getJson(String url) throws ClientProtocolException, IOException {
StringBuilder build = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpResponse response = client.execute(httpGet);
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String con;
while ((con = reader.readLine()) != null) {
build.append(con);
}
return build.toString();
}
}
You should not try to cram everything into a String. There are better data structures to hold multiple values: array, Vector, List, etc. Declare your AsyntTask as:
public class calculate extends AsyncTask<String, String, String[]>
and then your doInBackgorund method would be something like this:
#Override
protected String doInBackground(String... params) {
String[] result = new String[numResults];
...
result[0] = usjObj.getJSONObject("query").getJSONObject("results").getJSONObject("rate").getString("Rate");
...
result[1] = usjObj.getJSONObject("query").getJSONObject("results").getJSONObject("rate").getString("Rate");
...
return result;
}
And finally your onPostExecute would be
#Override
protected void onPostExecute(String[] usResult) {
...
}

Asynctask android return contents "doinBackground

I would like to retrieve the contents of my variable "$content" in my activity.
But I don't know how to use the return value of my doinbackground.
Can you help me ?
thank you in advance
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String restURL = "https://proxyepn-test.epnbn.net/wsapi/epn";
RestOperation test = new RestOperation();
test.execute(restURL);
}
private class RestOperation extends AsyncTask<String, Void, String> {
//final HttpClient httpClient = new DefaultHttpClient();
String content;
String error;
ProgressDialog progressDialog = new ProgressDialog(MainActivity.this);
String data = "";
TextView serverDataReceived = (TextView)findViewById(R.id.serverDataReceived);
TextView showParsedJSON = (TextView) findViewById(R.id.showParsedJSON);
// EditText userinput = (EditText) findViewById(R.id.userinput);
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog.setTitle("Please wait ...");
progressDialog.show();
}
#Override
protected String doInBackground(String... params) {
BufferedReader br = null;
URL url;
try {
url = new URL(params[0]);
URLConnection connection = url.openConnection();
connection.setDoOutput(true);
OutputStreamWriter outputStreamWr = new OutputStreamWriter(connection.getOutputStream());
outputStreamWr.write(data);
outputStreamWr.flush();
br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
while((line = br.readLine())!=null) {
sb.append(line);
sb.append(System.getProperty("line.separator"));
}
content = sb.toString();
} catch (MalformedURLException e) {
error = e.getMessage();
e.printStackTrace();
} catch (IOException e) {
error = e.getMessage();
e.printStackTrace();
} finally {
try {
br.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return content;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
progressDialog.dismiss();
if(error!=null) {
serverDataReceived.setText("Error " + error);
} else {
serverDataReceived.setText(content);
String output = "";
JSONObject jsonResponse;
try {
jsonResponse = new JSONObject(content);
JSONArray jsonArray = jsonResponse.names();
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject child = jsonArray.getJSONObject(i);
String name = child.getString("name");
String number = child.getString("number");
String time = child.getString("date_added");
output = "Name = " + name + System.getProperty("line.separator") + number + System.getProperty("line.separator") + time;
output += System.getProperty("line.separator");
Log.i("content",content);
}
showParsedJSON.setVisibility(View.INVISIBLE);
showParsedJSON.setText(output);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
You can directly call to the method which exist in activity, from onPostExecute method of asynctask by passing "content" value.
#Override
protected void onPostExecute(String content) {
Activity.yourMethod(content);
}
If you want to return the value from asynctask you can use
content = test.execute(url).get();
but it is not a good practice of asynctask, because it is working as serial execution. So it is not fulfill the use of asynctask for palatalization.Because get() will block the UI thread.

fetching the values from web api to andorid spinner

here my code for fetching values from web api. in my code no error is there. but in emulator doesn't show the values. please tell me where i done a mistake. let me know what is the correct code for that.
public class MainActivity extends ActionBarActivity {
Spinner sp1;
String url1=" http://www.cartrade.com/testmobileapplication/GetTopCitiesList.php? app_id=<random number>&action=Get Cities";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Spinner sp1=(Spinner)findViewById(R.id.spinner1);
}
public class Mysync extends AsyncTask<List<String>, List<String>, List<String>>{
#Override
protected List<String> doInBackground(List<String>... arg0) {
// TODO Auto-generated method stub
HttpClient httpclient = new DefaultHttpClient();
// Prepare a request object
HttpGet httpget = new HttpGet(url1);
// Execute the request
HttpResponse response;
JSONArray arr = new JSONArray();
try {
response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
if (entity != null && response.getStatusLine().getStatusCode() == 200) {
// A Simple JSON Response Read
InputStream instream = entity.getContent();
String result = convertStreamToString(instream);
arr=new JSONArray(result);
instream.close();
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
// Log.e(TAG,e.toString());
} catch (IOException e) {
// TODO Auto-generated catch block
// Log.e(TAG,e.toString());
} catch (JSONException e) {
// TODO Auto-generated catch block
//Log.e(TAG,e.toString());
}
List<String> list = new ArrayList<String>();
for(int i = 0; i < arr.length(); i++){
try {
list.add(arr.getJSONObject(i).getString("name"));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return list;
}
protected void onPostExecute(List<String> result){
sp1=(Spinner)findViewById(R.id.spinner1);
ArrayAdapter<String> adapter=new ArrayAdapter<String>(getApplicationContext(), R.layout.support_simple_spinner_dropdown_item);
sp1.setAdapter(adapter);
}
}
public String convertStreamToString(InputStream is) {
// TODO Auto-generated method stub
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
// Log.e(TAG + "ERROR",e.toString());
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
// Log.e(TAG + "ERRO",e.toString());
}
}
return sb.toString();
}
}
Define List under the line
String url1=" http://www.cartrade.com/testmobileapplication/GetTopCitiesList.php? app_id=&action=Get Cities";
like : List<String> list ;
And Try to Change the line
List list = new ArrayList();
Via
list = new ArrayList();
and Change
ArrayAdapter<String> adapter=new ArrayAdapter<String>(getApplicationContext(), R.layout.support_simple_spinner_dropdown_item);
Via
ArrayAdapter<String> adapter=new ArrayAdapter<String>(getApplicationContext(), R.layout.support_simple_spinner_dropdown_item,result);
Hope this may help you!

In case of exception in asynctask, how do i post the error message on UI?

I am trying to hit a url through asynctask class and some times, url might not be reachable, in such cases application crashes, how do i prevent this from happening, I would like to display an error message/Toast on UI..I tried to implement runOnUiThread(), but was not successful.
This is my asynctask class: In this case I will be gettin IOException.
public class SelectedEmployeeAsyncTask extends AsyncTask<String, Void, ArrayList<Employee>>{
private CaptureActivity captureActivity;
public SelectedEmployeeAsyncTask(CaptureActivity activity) {
this.captureActivity = activity;
}
#Override
protected ArrayList<Employee> doInBackground(String... url) {
ArrayList<Employee> employees = null;
for(String employeeUrl : url){
employees = fetch(employeeUrl);
}
return employees;
}
private ArrayList<Employee> fetch(String url) {
ArrayList<Employee> employees = null;
String response = null;
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
response = EntityUtils.toString(httpEntity);
employees = EmployeeXMLParser.selectedEmployeeParser(response);
System.out.println("Size in fetch "+employees.size());
//System.out.println("Employee Name :: " + employees.get(0).getFirstName() + " " + employees.get(0).getLastName());
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} /*catch (XmlPullParserException e) {
// TODO Auto-generated catch block
System.out.println("Error parsing the response :: " + response);
e.printStackTrace();
}*/
return employees;
}
#Override
public void onPostExecute(ArrayList<Employee> employees){
super.onPostExecute(employees);
System.out.println("in post execxute "+employees.size());
//progressDialog.dismiss();
captureActivity.display(employees);
//activity.showEmployees(employees);
//activity.setContentView(R.layout.activity_capture);
}
}
This is my activity class, where asynctask would be called:
public class CaptureActivity extends Activity {
//private String url = "http://192.168.3.140:8080/EmployeeXmlDemo/EmployeeList.xml";
private String url = "http://192.168.2.223:8680/capture/clientRequest.do?r=employeeList&cid=0";
FetchEmployeeAsyncTask employeeAsyncTask;
private ArrayList<Employee> employees = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitle("");
//if(employees!=null){
employeeAsyncTask = new FetchEmployeeAsyncTask(this);
//selectedEmployeeAsyncTask = new SelectedEmployeeAsyncTask(this);
employeeAsyncTask.execute(url);
setContentView(R.layout.activity_capture);
System.out.println("Status "+employeeAsyncTask.getStatus());
//}
}
try this,
catch (final Exception e) {if (e != null) {
e.printStackTrace();
Temes.this.runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(),e.toString(),Toast.LENGTH_LONG).show();
}
});
}

Json MySql get Two Integers and a String

Here is the class where i get JSON objects. In this code I get only one object and I don't really know how to return from the method, there is a Protected Void method where it is a settext method called and there is where the only JSON object goes.
public class ConnectMySql extends Activity {
TextView httpStuff;
HttpClient client;
JSONObject json;
final static String URL = "http://79.114.48.119/RadarsMySql.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
httpStuff = (TextView) findViewById(R.id.tvHttp);
client = new DefaultHttpClient();
new Read().execute("latitude");
}
public JSONObject lastTweet(String username) throws ClientProtocolException, IOException,JSONException{
StringBuilder url = new StringBuilder(URL);
url.append(username);
HttpGet get = new HttpGet(url.toString());
HttpResponse r = client.execute(get);
int status = r.getStatusLine().getStatusCode();
//if(status == 200){
HttpEntity e = r.getEntity();
String data = EntityUtils.toString(e);
data = data.substring(data.indexOf("["));
JSONArray timeline = new JSONArray(data);
JSONObject last = timeline.getJSONObject(0);
return last;
//}else{
//Toast.makeText(ConnectMySql.this, "error", Toast.LENGTH_LONG);
//return null;
//}
}
public class Read extends AsyncTask<String, Integer, String>{
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
try {
json = lastTweet("");
return json.getString(params[0]);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
public void onPostExecute(String result) {
// TODO Auto-generated method stub
httpStuff.setText(result);
int myNum = 0;
try {
myNum = Integer.parseInt(result);
httpStuff.setText(myNum);
} catch(NumberFormatException nfe) {
System.out.println("Could not parse " + nfe);
}
}
}
}
What I want to do is to have an array where i could store three kind of objects (exemple Latitude[1], Longitude [1], Description[1]; Latitude[2] etc... I would like the latitude and longitude to be as integers ). After this I will use a for loop to call a function with this 3 parameters. Could anyone help me or could give me some tips ?
Thank you!
Dont use AsyncTask, as it executes in background, and this is why it causes some problems for you.
And when you have your twitter arser working, integrate it in a AsyncTask. Code below is not tested.
public class ConnectMySql extends Activity {
TextView httpStuff;
HttpClient client;
int i;
JSONObject json;
final static String URL = "http://localhost/RadarsMySql.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
httpStuff = (TextView) findViewById(R.id.tvHttp);
client = new DefaultHttpClient();
for(i=0;i<2;i++){
new Read().execute("latitude");
try {
json = lastTweet("",i);
String result = json.getString(params[i]);
httpStuff.setText(result);
int myNum = 0;
try {
myNum = Integer.parseInt(result);
httpStuff.setText(myNum);
} catch(NumberFormatException nfe) {
System.out.println("Could not parse " + nfe);
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public JSONObject lastTweet(String username,int i) throws ClientProtocolException, IOException,JSONException{
StringBuilder url = new StringBuilder(URL);
url.append(username);
HttpGet get = new HttpGet(url.toString());
HttpResponse r = client.execute(get);
int status = r.getStatusLine().getStatusCode();
//if(status == 200){
HttpEntity e = r.getEntity();
String data = EntityUtils.toString(e);
data = data.substring(data.indexOf("["));
JSONArray timeline = new JSONArray(data);
JSONObject last = timeline.getJSONObject(i);
return last;
//}else{
//Toast.makeText(ConnectMySql.this, "error", Toast.LENGTH_LONG);
//return null;
//}
}
}

Categories

Resources