How do I check the contents of a String Builder - java

I am trying to parse some JSON and send it to a EditText field in my android application. I recently discovered that an error I was getting was stemming from the contents of my StringBuilder. Instead of using my StringBuilder I hardcoded a sample of json into a string and sent that to the EditText field. That works fine and I get the value I am looking for to show up. However I need this to work via accessing the API I am using and not hardcoding. Below is my JSON Parser class. Is there a way I can check what is in my stringBuilder after the append before inputStream is closed. This way I can sort that out and return my jSon back to stringBuilder.toString() instead of hardcoding it.
package com.apitest.rottentomatoestest;
import java.io.*;
import org.apache.http.*;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.*;
import android.util.Log;
public class JSONParser {
static InputStream inputStream = null;
static JSONObject jObject = null;
static String jSon = "";
public JSONParser() {
// TODO Auto-generated constructor stub
}
public JSONObject getJSONFromUrl(String url){
//Make HTTP Request
try {
//defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
inputStream = httpEntity.getContent();
} catch (UnsupportedEncodingException e){
e.printStackTrace();
} catch (ClientProtocolException e){
e.printStackTrace();
}catch (IOException e){
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder stringBuilder = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null){
stringBuilder.append(line + "\n");
}
inputStream.close();
jSon = "{\"cast\":[{\"id\":\"162661723\",\"name\":\"Snoop Dogg\"}]}";
} catch (Exception e){
Log.e("Buffer Error", "Error converting result " + e.toString());
}
//try to parse the string to JSON Object
try {
jObject = new JSONObject(jSon);
} catch (JSONException e){
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
//return JSON String
return jObject;
}
}

You can use:
Log.d("JSON Contents", stringBuilder.toString());
just before you close the inputStream.
Update: The 596 Service Not Found message is often caused by an incorrect URL.

try doing this instead :
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));

You can use org.json.JSONObject for parsing JSON into usable Java Object.

Related

Error parsing dataorg.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject

i'm trying to make android food order for my thesis and because this error i'm running out of time :(
error on logcat :
Error parsing dataorg.json.JSONException: Value cannot be converted to JSONObject
org.json.JSONException: Value to JSONObject
here's my JSONParser :
package com.makanan.restotradisional;
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.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
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 = "";
public JSONParser() {
}
// fungsi abil json url lewat method HTTP POST atau GET
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
try {
if (method == "POST") {
// jika request method adalah 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") {
// jika request method adalah 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());
e.printStackTrace();
}
return jObj;
}
}
this my PHP & Java : http://www.4shared.com/rar/1lGplX19ba/Java_and_PHP.html
and this is my database on phpmyadmin :http://www.4shared.com/rar/y_UMtL7_ce/rumah_makan.html
please help me
Remove any of the <br> statements or echo statements from your php file except the one that you are using to pass json..
Check the output of your file in browser, remove all the unwanted things other than json..
Please print and check if your string json is in right format as expected by the JSONObject constructor. Per documentation, valid json string to construct JSONObject should be -- A string beginning with { (left brace) and ending with } (right brace).
Please refer this.
Go inside JSONParser and do this so u see in logcat whats comming from php. Probably its a php error.
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
//This line is what u need to add
Log.d("Whats wrong?", json.toString());
Log.e("JSON Parser", "Error parsing data " + e.toString());
}

Android: httppost Illegal character in query at index

Im trying to parse the json returned from graph facebook, a feed from a page.
The url is something like this: https://graph.facebook.com/pageId/feed?access_token=MyAppId|MySecretKey&limit=10.
But I'm getting the error: Illegal character in query at index 7. The character at index 77 it's the "|". My code:
private JSONObject getJSONFromUrl(String url) throws UnsupportedEncodingException {
// Making HTTP request
InputStream is = null;
JSONObject jObj = null;
String json = "";
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
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();
} 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;
}
If I replace the URL, using the encoder, like this:
String url = "https://graph.facebook.com/pageId/feed?access_token=MyAppId" + URLEncoder.encode("|", "UTF-8") + "mySecretKey&limit=10";
I receive the error:
{"error":{"message":"(#200) The user hasn't authorized the application to perform this action","type":"OAuthException","code":200}}
But If I copy and paste the original URL, it's returning successfully the JSON
How can I send correctly the url on this case?

Error JSON Parser android app

I have a small problem with my code and I can't find why. I get the error parsing data for my email value.
The exact error is :
Error parsing data org.json.JSONException: Value Mail of type java.lang.String cannot be converted to JSONObject.
It happens after having the Log.d(request!, starting)
Here are the code.
Activity.java:
package com.example.mysqltest;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class ForgotPassword extends Activity implements OnClickListener{
private EditText email;
private Button mForgotPassword;
// Progress Dialog
private ProgressDialog pDialog;
// JSON parser class
JSONParser jsonParser = new JSONParser();
//php register script
private static final String REGISTER_URL = "test";
//ids
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_forgot_password);
email = (EditText)findViewById(R.id.emailforf);
mForgotPassword = (Button)findViewById(R.id.forgotPassword);
mForgotPassword.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
new ForgotPass().execute();
}
class ForgotPass extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(ForgotPassword.this);
pDialog.setMessage("Retrieving password...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
// Check for success tag
int success;
String emails = email.getText().toString();
if (emails instanceof String){
Log.d("lol","ok");
}else{
Log.d("lol","not ok");
}
try {
// Building Parameters
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(ForgotPassword.this);
String userpref = prefs.getString("username","arnaud");
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("emailForgot", emails));
Log.d(userpref,"lol");
params.add(new BasicNameValuePair("username", userpref));
Log.d("request!", "starting");
//Posting user data to script
JSONObject json = jsonParser.makeHttpRequest(
REGISTER_URL, "POST", params);
// full json response
Log.d("Registering attempt", json.toString());
// json success element
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Log.d("User Created!", json.toString());
finish();
return json.getString(TAG_MESSAGE);
}else{
Log.d("Registering Failure!", json.getString(TAG_MESSAGE));
return json.getString(TAG_MESSAGE);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
// dismiss the dialog once product deleted
pDialog.dismiss();
if (file_url != null){
Toast.makeText(ForgotPassword.this, file_url, Toast.LENGTH_LONG).show();
}
}
}
}
JSONParser.java :
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.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
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(final String url) {
// Making HTTP request
try {
// Construct the client and the HTTP request.
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
// Execute the POST request and store the response locally.
HttpResponse httpResponse = httpClient.execute(httpPost);
// Extract data from the response.
HttpEntity httpEntity = httpResponse.getEntity();
// Open an inputStream with the data content.
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
// Create a BufferedReader to parse through the inputStream.
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
// Declare a string builder to help with the parsing.
StringBuilder sb = new StringBuilder();
// Declare a string to store the JSON object data in string form.
String line = null;
// Build the string until null.
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
// Close the input stream.
is.close();
// Convert the string builder data to an actual string.
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// Try to 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 the JSON Object.
return jObj;
}
// 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();
} 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;
}
}
Thanks for any help.
[Edit] Here is my web service :
<?php
try {
$to = $_POST['emailForgot'];
$subject = "Test mail";
$message = "Hello! This is a simple email message.";
$from = "track_my_mate#example.com";
$headers = "From:" . $from;
mail($to,$subject,$message,$headers);
echo "Mail Sent.";
$randome = 'pierre';
$query = "UPDATE 'users' SET 'password' = ? WHERE 'id' = ? ";
//Again, we need to update our tokens with the actual data:
$query_params = array(
':pass' => $randome,
':user' => $_POST['username']
);
//time to run our query, and create the user
try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch (PDOException $ex) {
// For testing, you could use a die and message.
//die("Failed to run query: " . $ex->getMessage());
//or just use this use this one:
$response["success"] = 0;
$response["message"] = "Database Error2. Please Try Again!";
die(json_encode($response));
}
} catch (Exception $e) {
$response["success"] = 0;
$response["message"] = "Please Try Again!";
}
//If we have made it this far without dying, we have successfully added
//a new user to our database. We could do a few things here, such as
//redirect to the login page. Instead we are going to echo out some
//json data that will be read by the Android application, which will login
//the user (or redirect to a different activity, I'm not sure yet..)
$response["success"] = 1;
$response["message"] = "Password Successfully Changed!";
try {
echo json_encode($response);
} catch (Exception $e) {
echo ("pierre");
}
//for a php webservice you could do a simple redirect and die.
//header("Location: login.php");
//die("Redirecting to login.php");
//}
?>
[EDIT2] I get : Mail Sent. {"success":0,"message":"Database Error2. Please Try Again !"} The problem is in my query I guess?
Arnaud
From server side,
you need to send
{"success":0,"message":"Database Error2. Please Try Again !"}
instead of
Mail Sent. {"success":0,"message":"Database Error2. Please Try Again !"}
get JSONException: Value of type java.lang.String cannot be converted to JSONObject when parsing a JSON response
Likely that your web service is not returning correct JSON.
i wanted to put some comment but i should have at list 50 reputation!!! so i should give my answer here... i had same problem with json object. use "GET" method instead of "POST". try it...
USE THIS JSON PARSER
public class JSONParser extends Activity{
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) {
Log.e("JSON PARSER", "GET OR POST");
Toast.makeText(getApplicationContext(), "Something is wrong with network!", Toast.LENGTH_LONG).show();
json="";
create_JSon_Object();
} catch (ClientProtocolException e) {
Toast.makeText(getApplicationContext(), "Something is wrong with network!", Toast.LENGTH_LONG).show();
Log.e("JSON PARSER", "GET OR POST");
json="";
return create_JSon_Object();
} catch (IOException e) {
Toast.makeText(getApplicationContext(), "Something is wrong with network!", Toast.LENGTH_LONG).show();
Log.e("JSON PARSER IO ERROR", "GET OR POST");
json="";
return create_JSon_Object();
}
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();
json = sb.toString();
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Something is wrong with network!", Toast.LENGTH_LONG).show();
Log.e("JSON PARSER Buffer Error", "Error converting result ");
json="";
return create_JSon_Object();
}
return create_JSon_Object();
}
private JSONObject create_JSon_Object() {
// try parse the string to a JSON object
try {
//jObj = new JSONObject(json);
jObj = new JSONObject(json);
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "Something is wrong with network!", Toast.LENGTH_LONG).show();
Log.e("JSON Parser", "Error parsing data " + e.toString());
return jObj;
}
// return JSON String
return jObj;
}
}

Source not found error after HttpClient.execute()

I am new to android development. I have the following class for downloading some data in JSON format. I keep getting a Source not found error on the
HttpResponse httpResponse = httpClient.execute(httpPost);
line... I'm sure this must be a simple fix... Here is the class code...
package com.example.tankandroid;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
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) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
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();
} 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;
}
}
Put this code in onCreate method
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
Use Apache HttpCore and HttpClient libraries. Put these two libraries into your lib folder, its automatically add these into your build path.
One reason for this situation may be missing internet permissions in AndroidManifest.xml file. Adding this line in manifest will fix the issue.
<uses-permission android:name="android.permission.INTERNET" />
You need to provide some more information I think. Where do you get the "Source not found" error? Is it an Eclipse error that prevents you from compiling. Is it during compilation? Is it a runtime error? Could this be a possible duplicate of: Source not found Android? ?
Question: Why are you doing an HTTP POST if you don't intend to add any POST data? A GET seems more appropriate.
And since you also ask "I'm sure this must be a simple fix" then yes, it is. I'd really suggest that you rip out your HTTP code and switch to Android Asynchronous Http Client. It's super easy to work with and very well suited for getting an HTTP response and parsing it. Example:
AsyncHttpClient client = new AsyncHttpClient();
RequestParams rp = new RequestParams();
rp.put("some_param", "some value");
rp.put("another_param", "some other value");
client.post("http://www.simonsayssolutions.co.uk/index.php", rp, new AsyncHttpResponseHandler() {
#Override
public final void onSuccess(String response) {
// handle your response and parse JSON here
}
#Override
public void onFailure(Throwable e, String response) {
// something went wrong
}
});
or GET:
client.get("http://www.simonsayssolutions.co.uk/index.php", rp, new AsyncHttpResponseHandler() {
...
}
And finally if you want to simplify JSON parsing have a look at Jackson or Gson. Especially if you want to parse JSON data to Java objects and vice versa.

why am I getting a MalformedURLException

I am not sure why this url is throwing a MalformedURL exception: http%3A%2F%2Fapi.themoviedb.org%2F3%2Fsearch%2Fperson%3Fapi_key%3secret%26query%3Dchristopher_guest
This is the url required by the api that I need to use. http://api.themoviedb.org/3/search/person?api_key=secret&query=christopher_guest
I have been getting target host must not be null errors using this url then I changed my coded to what you are seeing below. Not sure whats going on here although I have heard urls that contain underscores dont validate outside of web browsers and cause these types of situations.
Any ideas around this?
This is where I build the url
package com.tot.tipofthetongue;
import android.widget.EditText;
public class getName {
static String nameOne = null;
static String nameTwo = null;
static StringBuilder personURLOne = new StringBuilder();
static StringBuilder personURLTwo = new StringBuilder();
public static String personURL = "http://api.themoviedb.org/3/search/person?api_key=secret&query=";
public static StringBuilder getName1(EditText searchOne){
nameOne = searchOne.getText().toString();
nameOne = nameOne.replace(" ", "_");
personURLOne.append(personURL);
personURLOne = personURLOne.append(nameOne);
return personURLOne;
}
And this is my jsonparser that I pass that url to.
public class JSONParser extends AsyncTask<String, Void, JSONObject> {
static InputStream inputStream = null;
static JSONObject jObject = null;
static String jSon = "";
public String myURL;
String host;
HttpRequest request;
protected JSONObject doInBackground(String... url) {
// TODO Auto-generated method stub
//Make HTTP Request
try {
//defaultHttpClient
for(int i = 0; i < url.length; i++){
myURL = url[0];
myURL = URLEncoder.encode(myURL, "utf-8");
}
HttpGet httpGet = new HttpGet(myURL);
//header
httpGet.setHeader("Accept", "application/json");
HttpResponse httpResponse = new DefaultHttpClient().execute(new HttpHost(new URL(myURL).getHost()), request);
HttpEntity httpEntity = httpResponse.getEntity();
inputStream = httpEntity.getContent();
} catch (UnsupportedEncodingException e){
e.printStackTrace();
} catch (ClientProtocolException e){
e.printStackTrace();
}catch (IOException e){
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder stringBuilder = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null){
stringBuilder.append(line + "\n");
}
Log.d("JSON Contents", stringBuilder.toString());
inputStream.close();
jSon = stringBuilder.toString();
} catch (Exception e){
Log.e("Buffer Error", "Error converting result " + e.toString());
}
//try to parse the string to JSON Object
try {
jObject = new JSONObject(jSon);
} catch (JSONException e){
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
//return JSON String
return jObject;
}
}
Print the String you formed before final submission to form Uri. And attach this to your question. It would be much easier to answer.
Try using HttpGet(URI uri) instead of HttpGet(String uri)
The reason is pretty simple. If you are using Uri, you will get immediately the Exception.
Hope this will help you to debug quickly.

Categories

Resources