inputstream restful api is returning null - java

anyone knows why InputStream responseBody = conn.getInputStream(); gives me null ?
basically, the error here is in the first few lines of code.
I have a restful API XML link that i am trying to parse as a JSON object.
And the logcat isn't being very helpful.
Any help would be greatly appreciated
thank you
ArrayList<Camera> cameras = new ArrayList<>();
try {
url = new URL("http://192.168.1.6:50323/Cam_Sql/webresources/com.mycompany.cam_sql.camerasfrench/1/250");
} catch (MalformedURLException e) {
e.printStackTrace();
}
URLConnection conn = null;
try {
conn = url.openConnection();
InputStream responseBody = conn.getInputStream();
InputStreamReader responseBodyReader = new InputStreamReader(responseBody, "UTF-8");
JSONObject jsonObj = null;
jsonObj = XML.toJSONObject(responseBodyReader.toString());
JsonReader jsonReader = new JsonReader(responseBodyReader);
jsonReader.beginObject(); // Start processing the JSON object
String cameraLong = null;
String cameraId = null;
String cameraName = null;
String cameraLat = null;
while (jsonReader.hasNext()) { // Loop through all keys
String key = jsonReader.nextName(); // Fetch the next key
if (key.equals("camId")) { // Check if desired key
// Fetch the value as a String
cameraId = jsonReader.nextString();
} else if (key.equals("camName")) {
cameraName = jsonReader.nextString();
} else if (key.equals("cameraLong")) {
cameraLong = jsonReader.nextString();
} else if (key.equals("cameraLat")) {
cameraLat = jsonReader.nextString();
cameras.add(new Camera(cameraName, cameraId, cameraLong, cameraLat));
// Do something with the value
// ...
break; // Break out of the loop
} else {
jsonReader.skipValue(); // Skip values of other keys
}
}
} catch (JSONException e) {
System.out.println(e.toString());
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
/*
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
String db = null;
try {
Class.forName("net.sourceforge.jtds.jdbc.Driver");
Connection dbCon = DriverManager.getConnection("jdbc:jtds:sqlserver://traffic-cam.database.windows.net:1433/Android;user=tyler#traffic-cam;password=Password!;");
// db = dbCon.toString();
int i = 0; //iterator
int rows = 0;
Statement stmt = dbCon.createStatement();
String query = "SELECT COUNT(*) FROM CamerasFrench;";
ResultSet rs = stmt.executeQuery(query);
if(rs.next()){
rows = Integer.parseInt(rs.getString(1)); //gets the amount of rows in database
}
//camInfo = new String[rows][4];
stmt = dbCon.createStatement();
query = "SELECT * FROM CamerasFrench;";
rs = stmt.executeQuery(query);
while(rs.next()){ //goes through every row, puts the data into the 2d array
String cameraName = rs.getString("cam_name");
String cameraLong = rs.getString("cam_longitude");
String cameraLat = rs.getString("cam_latitude");
String cameraId = rs.getString("cam_id");
if (getResources().getConfiguration().locale.getLanguage() == "fr") {
cameraName = rs.getString("cam_frName");
}
cameras.add(new Camera(cameraName, cameraId, cameraLong, cameraLat));
//i++;
//System.out.println("List Size: "+cameras.size());
}
}
catch (Exception e){
System.out.println(e.getMessage());
}
*/
if (cameras.size() > 0) {
Collections.sort(cameras, new Comparator<Camera>() {
#Override
public int compare(final Camera object1, final Camera object2) {
return object1.getCameraName().compareTo(object2.getCameraName());
}
});
}
return cameras;
}

First of all sorry for bad English.
Basically, null pointer exception is very easy to find where this error came from.
Check your connection is successfully connected or not.
below is reference code.
HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
// this is option.
urlConnection.setReadTimeout(30000);
urlConnection.setConnectTimeout(30000);
urlConnection.setRequestMethod("GET");
urlConnection.setUseCaches(false);
urlConnection.setAllowUserInteraction(false);
urlConnection.setRequestProperty("Content-Type", "application/json");
int responceCode = urlConnection.getResponseCode();
if (responceCode == HttpURLConnection.HTTP_OK) {} // using here. conn.getInputStream()

Related

Is there a way that I can return arrays without String[] params?

public class PerformNetworkTasks extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect(); //getting the connection to the URL to read JSON data
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String jsonText = buffer.toString(); // gets what the URL returns as JSON
JSONObject obj = new JSONObject(jsonText); // using JSONObject to pass to a JSONArray to search for the JSON
List<String> allInfo = new ArrayList<String>(); // list to put all the returned information
JSONArray linemanques = obj.getJSONArray("linemanques"); //selects the array to read from
for (int i = 0; i < linemanques.length(); i++) {
JSONObject questionParts = linemanques.getJSONObject(i);
quesnum = questionParts.getString("quesnum"); // all of questionParts.getString() are for getting the data in the JSONArray
questype = questionParts.getString("questype");
question = questionParts.getString("question");
ans1 = questionParts.getString("ans1");
ans2 = questionParts.getString("ans2");
ans3 = questionParts.getString("ans3");
ans4 = questionParts.getString("ans4");
correctans = questionParts.getString("correctans");
category = questionParts.getString("category");
notes = questionParts.getString("notes");
flag = questionParts.getString("flag");
allInfo.add(quesnum);
allInfo.add(questype);
allInfo.add(question);
allInfo.add(ans1);
allInfo.add(ans2);
allInfo.add(ans3);
allInfo.add(ans4);
allInfo.add(correctans);
allInfo.add(category);
allInfo.add(notes);
allInfo.add(flag);
allInfo.add("\n");
}
return allInfo.toString();
/*
right now I am returning the list as a String,
so that I can actually view the data.
I need to put this data into their own TextViews.
So how can I return the list I have so that I can set
the individual TextViews as one section from the list?
*/
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
}
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
inputDataTV.setText(result);
}
I need to return some data individually. So I need to return an array (i think) so that I can set the TextView as e.g. arrays.get(number).
Is there some other way that I am not realizing here, or should I continue with what I am doing to get the data individually?
Just to add, I am getting the info from a website.
You can return any data type you want
but your AsyncTask structure should be based on result data type
public class PerformNetworkTasks extends AsyncTask<String, String, List<String>/*resultParam*/> {
#Override
protected List<String>/*will same as result parma*/ doInBackground(String... params) {
return null;/*now you can return list of string*/
}
#Override
protected void onPostExecute(List<String>/*finally receive result*/ result) {
super.onPostExecute(result);
}
}
so your code will be
public class PerformNetworkTasks extends AsyncTask<String, String, List<String>> {
#Override
protected List<String> doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect(); //getting the connection to the URL to read JSON data
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String jsonText = buffer.toString(); // gets what the URL returns as JSON
JSONObject obj = new JSONObject(jsonText); // using JSONObject to pass to a JSONArray to search for the JSON
List<String> allInfo = new ArrayList<>(); // list to put all the returned information
JSONArray linemanques = obj.getJSONArray("linemanques"); //selects the array to read from
for (int i = 0; i < linemanques.length(); i++) {
JSONObject questionParts = linemanques.getJSONObject(i);
quesnum = questionParts.getString("quesnum"); // all of questionParts.getString() are for getting the data in the JSONArray
questype = questionParts.getString("questype");
question = questionParts.getString("question");
ans1 = questionParts.getString("ans1");
ans2 = questionParts.getString("ans2");
ans3 = questionParts.getString("ans3");
ans4 = questionParts.getString("ans4");
correctans = questionParts.getString("correctans");
category = questionParts.getString("category");
notes = questionParts.getString("notes");
flag = questionParts.getString("flag");
allInfo.add(quesnum);
allInfo.add(questype);
allInfo.add(question);
allInfo.add(ans1);
allInfo.add(ans2);
allInfo.add(ans3);
allInfo.add(ans4);
allInfo.add(correctans);
allInfo.add(category);
allInfo.add(notes);
allInfo.add(flag);
allInfo.add("\n");
}
return allInfo;
/*
right now
I am returning the list as a String,
so that I can actually view the data.
I need to put this data into their own TextViews.
So how can I return the list I have so that I can set
the individual TextViews as one section from the list?
*/
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
}
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(List<String> result) {
super.onPostExecute(result);
inputDataTV.setText(result.get(0));
}
}

How to get weather data from api?

I'm new in android.I want to create a weather app that gets data from weather app by api.I write the api code.,but it doesn't work it and it doesn't show in logcat too. I added JsonObject and jsonPart but it doesn't show .First i tried in Log and then device but it doesn't show at all.
public class DownloasTask extends AsyncTask<String,Void,String>{
#Override
at a protected String doInBackground(String... urls) {
String result ="";
URL url;
HttpURLConnection urlConnection = null;
try{
url = new URL(urls[0]);
urlConnection =(HttpURLConnection) url.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(in);
int data = reader.read();
while (data !=1){
char current = (char) data;
result = result +current;
data =reader.read();
}
return result;
}catch (Exception e){
e.printStackTrace();
Log.i("Exception"," url failed");
Toast.makeText(getApplicationContext(),"Could not find the weather",Toast.LENGTH_SHORT).show();
return null;
}
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
try{
JSONObject jsonObject = new JSONObject(result);
String weatherInfo = jsonObject.getString("weather");
JSONArray arr = new JSONArray(weatherInfo);
String message ="";
for(int i = 0;i<arr.length();i++){
JSONObject jsonPart =arr.getJSONObject(i);
String main =jsonPart.getString("main");
String description =jsonPart.getString("description");
if(!(main.equals("")) && !description.equals("")){
message +=main +": "+description+"\r\n";
}
Log.i("main",jsonPart.getString("main"));
Log.i("description",jsonPart.getString("description"));
}
if(!message.equals("")){
textView2.setText(message);
}else {
Toast.makeText(getApplicationContext(),"Could not find the weather",Toast.LENGTH_SHORT).show();
}
}catch (Exception e){
e.printStackTrace();
Log.i("jsonobject", "onPostExecute: ");
Toast.makeText(getApplicationContext(),"Could not find the weather",Toast.LENGTH_SHORT).show();
}
}
}
public void getWeather(View view){
DownloasTask task = new DownloasTask()
task.execute("https://openweathermap.org/data/2.5/forecast?q=" +
editText.getText().toString() +
"&appid=b1b15e88fa797225412429c1c50c122a1");
InputMethodManager inputMethodManager =
(InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(editText.getWindowToken(),0);
}
}

Save search results into JTable

//I try to make an function for catching all results of search of some string, //but I only catching one element and my for does not continue to all results of //my search.
//There is an error in my loop sequence?
//Do you have any soggestion?
//This is my code.
//Sorry my code it is in spanish.
private void Buscar(String tema){
String url = "http://www.google.com/search?q="+tema;
String resultado;
String[] resultados;
DefaultTableModel model = (DefaultTableModel) jT_ResultadosBusqueda.getModel();
int contacampos;
try{
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("User-Agent", USER_AGENT);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
StringBuffer response = new StringBuffer();
while ((tema = in.readLine()) != null) {
response.append(tema);
}
in.close();
resultado = response.toString();
resultados = resultado.split("<a href=\"/url?q=");
contacampos = 1;
do{
for (int i = 0; i < resultados.length; i++) {
//JOptionPane.showMessageDialog(this,i);
//JOptionPane.showMessageDialog(this,resultados.length);
int inicio = resultados[i].indexOf("\"http");
//JOptionPane.showMessageDialog(this,inicio);
int fondo = resultados[i].indexOf("\">");
//JOptionPane.showMessageDialog(this,fondo);
String result = resultados[i].substring(inicio + 1, fondo);
model.addRow(new Object[]{result,"Ejemplo1","Tema1","Asunto1","www.1.com"});
}
contacampos = contacampos +1;
}while(contacampos<resultados.length);
}catch(HeadlessException | IOException e){
JOptionPane.showMessageDialog(this,e.getMessage (),"¡Aviso!",JOptionPane.ERROR_MESSAGE);
}
}
The solution it was Jsoup.
This is my actual code.
private void Buscar(String tema){
try {
// TODO add your handling code here:
org.jsoup.nodes.Document doc = Jsoup.connect("http://www.google.com/search?q="+tema).get();
DefaultTableModel model = (DefaultTableModel) jT_ResultadosBusqueda.getModel();
//doc.title()
Elements link = doc.select("a[href]");
for (Element linkline : link) {
JOptionPane.showMessageDialog(this,linkline);
model.addRow(new Object[]{linkline.tagName(),linkline.id(),"","",""});
}
} catch (IOException ex) {
Logger.getLogger(Buscador.class.getName()).log(Level.SEVERE, null, ex);
}
}

Android Studio crash google Geo Api

I'm having a little problem with my app. It crashes and when I run it on Debug it doesn't say anything. This is where the crash occurs:
public class GeoTask extends AsyncTask<String,Void,ArrayList<Double>>{
#Override
protected ArrayList<Double> doInBackground(String... params) {
ArrayList<Double> geo_ll = new ArrayList<>();
HttpsURLConnection connection = null;
BufferedReader reader = null;
String result ="";
try {
URL url = new URL("https://maps.googleapis.com/maps/api/geocode/json?address=New York&key=AIzaSyBpaGooTWbj7QbN_qdW4pf-OvAi2OOhpG4");
connection = (HttpsURLConnection) url.openConnection();
int code = connection.getResponseCode();
int a = 1;
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK){
return null;
}
reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line = reader.readLine();
while(line!=null){
result+=line;
line = reader.readLine();
}
JSONObject object = new JSONObject(result);
JSONArray results = object.getJSONArray("results");
JSONObject zero = results.getJSONObject(0);
JSONObject geometry = zero.getJSONObject("geometry");
JSONObject location = geometry.getJSONObject("location");
double latitude = location.getDouble("lat");
double longitude = location.getDouble("lng");
geo_ll.add(latitude);
geo_ll.add(longitude);
return geo_ll;
} catch (MalformedURLException e) {
Toast.makeText(NewItemActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
Toast.makeText(NewItemActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
} catch (IOException e) {
Toast.makeText(NewItemActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
return null;
}
I can't see anything wrong. I have checked it more then 100 times and still it happens. It actually worked once and then never worked again after...
please help.
thank you for your time.

java.net.ProtocolException: content-length promised 16280 bytes, but received 16272

I want to send data as a string to an api from android app, but when I send large amount of data in string form it shows me this error "java.net.ProtocolException: content-length promised 16280 bytes, but received 16272" . And if I send small amount of data it don't give any error. Its saying something about content length mismatch and I am not getting it.
I am sharing you my code please check
enter code here
private class AsyncTaskRunner extends AsyncTask<Void,
Void, ArrayList<String[]>> {
private String resp;
#Override
protected void onPreExecute() {
super.onPreExecute();
progressBar = new ProgressDialog(getActivity());
progressBar.setCancelable(true);
progressBar.setMessage("Fetching Contacts ...");
progressBar.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressBar.show();
}
#Override
protected ArrayList<String[]> doInBackground(Void... params) {
ContentResolver cr = getActivity().getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
null, null, null, null);
// ArrayList<String[]> contacts = new ArrayList<String[]>();
if (cur.getCount() > 0) {
while (cur.moveToNext()) {
String id =cur.getString(cur.getColumnIndex
(ContactsContract.Contacts._ID));
String name = cur.getString(cur.getColumnIndex
(ContactsContract.Contacts.DISPLAY_NAME));
String phones = null;
if (Integer.parseInt(cur.getString(cur.getColumnIndex
(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
//Query phone here. Covered next
if (Integer.parseInt(cur.getString(cur.getColumnIndex
(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
Cursor pCur = cr.query(
ContactsContract.CommonDataKinds.Phone.
CONTENT_URI,null,
ContactsContract.CommonDataKinds.
Phone.CONTACT_ID + " = ?",
new String[]{id}, null);
while (pCur.moveToNext()) {
// Do something with phones
phones = pCur.getString(pCur.getColumnIndex
(ContactsContract.CommonDataKinds.Phone.NUMBER));
// String[] str = new String[3];
// str[0] = id;
// str[1] = name;
// str[2] = phones;
// contacts.add(str);
}
pCur.close();
}
}
String[] str = new String[3];
str[0] = id;
str[1] = name;
str[2] = phones;
long val1 = adapter1.insertContacts(id, name, phones);
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("name", name);
jsonObject.put("phones", phones);
jsonArray.put(jsonObject);
} catch (JSONException e) {
e.printStackTrace();
}
Log.d("value is", "" + val1);
contacts.add(str);
}
}
cur.close();
String name = "Siddhant";
String postjson = String.valueOf(jsonArray);
rsp = serviceResponse(postjson, Config.URL_SAVE_CONTACTS);
Collections.sort(contacts, ALPHABETICAL_ORDER);
mAllData.addAll(contacts);
return contacts;
}
private Comparator<String[]> ALPHABETICAL_ORDER =
new Comparator<String[]>()
{
#Override
public int compare(String[] lhs, String[] rhs) {
int res = String.CASE_INSENSITIVE_ORDER.compare(lhs[1], rhs[1]);
if (res == 0) {
res = lhs[1].compareTo(rhs[1]);
}
return res;
}
};
#Override
protected void onPostExecute(ArrayList<String[]> result) {
super.onPostExecute(result);
adapter = new ContactsListAdapter(getActivity(), contacts);
listView.setAdapter(adapter);
progressBar.dismiss();
if (rsp!=null) {
String json = rsp.toString();
Toast.makeText(getActivity(), json, Toast.LENGTH_SHORT).show();
}
}
}
public String serviceResponse(String postStr, String urlString) {
HttpURLConnection connection = null;
try {
// original code
// Create connection
URL url = new URL(urlString);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type",
"application/x-www- form-urlencoded");
// connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty
("Content-Length", "" +Integer.toString(postStr.getBytes().length));
connection.setRequestProperty("Content-Language", "en-US");
connection.setUseCaches(false);
connection.setDoOutput(false);
// Send request
DataOutputStream wr =
new DataOutputStream(connection.getOutputStream());
wr.writeBytes(postStr);
wr.flush();
wr.close();
int status = connection.getResponseCode();
// return String.valueOf(status);
InputStream is;
if (status >= HttpStatus.SC_BAD_REQUEST)
is = connection.getErrorStream();
else
is = connection.getInputStream();
// Get Response
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer response = new StringBuffer();
while ((line = rd.readLine()) != null) {
response.append(line);
}
rd.close();
return response.toString();
} catch (Exception e) {
e.getMessage();
return null;
} finally {
if (connection != null) {
connection.disconnect();
}
}
}
I think it is about getBytes()
Be careful when you use it because you have to pass the character encoding parameter like .getBytes("UTF-8")
If you don't pass any parameter it will use the system default.
My educated guess is that your data is not a standard UTF-8 data so you should give the correct character set and i think after that your data length will match.
Edit:
Now, I see your mistake.
When you set
wr.writeBytes(postStr);
It sets the encoding wrongly again :)
You should do something like that:
wr.write(postStr.getBytes("UTF-8"));
p.s: you should change "UTF-8" to anything that supports your language to get your data on the server side correctly.

Categories

Resources