How to change from Get Json Raw File to Get Json Url? - android

I have a code that works fine: Get Json from raw file (raw/video_list.json)
public class VideoListFragment extends BaseListFragment {
VideoAdapter adapter;
#Override
protected RecyclerView.Adapter getAdapter() {
if (adapter == null) {
String jsonStr = readRawFile();
Gson gson = new Gson();
VideoPage videoPage = gson.fromJson(jsonStr, VideoPage.class);
adapter = new VideoAdapter(videoPage);
}
return adapter;
}
String readRawFile() {
String content = "";
Resources resources = getContext().getResources();
InputStream is = null;
try {
is = resources.openRawResource(R.raw.video_list);
byte buffer[] = new byte[is.available()];
is.read(buffer);
content = new String(buffer);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return content;
}
}
Now I want to get Json from Url,I copy Json in the video_list.json file to myjson.com and then get the url (https://api.myjson.com/bins/uyzbl), I change code:
public class VideoListFragment extends BaseListFragment {
VideoAdapter adapter;
#Override
protected RecyclerView.Adapter getAdapter() {
if (adapter == null) {
String jsonStr = readData("https://api.myjson.com/bins/71535");
Gson gson = new Gson();
VideoPage videoPage = gson.fromJson(jsonStr, VideoPage.class);
adapter = new VideoAdapter(videoPage);
}
return adapter;
}
String readData(String url) {
HttpsURLConnection con = null;
try {
URL u = new URL(url);
con = (HttpsURLConnection) u.openConnection();
con.connect();
BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
br.close();
return sb.toString();
} catch (MalformedURLException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (con != null) {
try {
con.disconnect();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
return null;
}
}
No errors occurred in Android Studio but App unfortunately, app has stopped. Can you help me find and fix it?

Related

Android java json url from dropbox

I have this piece of code on android that reads data from Assets folder, so I need from this code to read data from external like dropbox. Ho to change and read data from dropbox. thanks
#Override
protected RadioDatas doInBackground(Void... params) {
BufferedReader reader = null;
ArrayList<RadioData> radioDatas = new ArrayList<>();
RadioDatas datas = new RadioDatas();
try {
reader = new BufferedReader(
new InputStreamReader(context.getAssets().open("url.txt"), "Unicode"));
String mLine;
while ((mLine = reader.readLine()) != null) {
RadioData radioData = new RadioData();
String[] meta = mLine.split(";");
radioData.setUrl(meta[0]);
radioData.setTitle(meta[1]);
radioData.setGenres(meta[2]);
radioDatas.add(radioData);
}
} catch (IOException e) {
//log the exception
return null;
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
//log the exception
}
}
}
datas.setRadioDatas(radioDatas);
return datas;
}
This would work....
public class Execute extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler handler = new HttpHandler();
String jsonString = handler.makeServiceCall(json);
if (jsonString != null) {
try {
//parse jsonString
} catch (JSONException e) {
Log.i("Error with parsing", e.getMessage());
}
}
return null;
}
protected void onPostExecute(Void result) {
super.onPostExecute(result);
}
}
You will need a HTTPHandler class...
public class HttpHandler {
private static final String TAG = HttpHandler.class.getSimpleName();
public HttpHandler() {
}
public String makeServiceCall(String reqUrl) {
String response = null;
try {
URL url = new URL(reqUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
// read the response
InputStream in = new BufferedInputStream(conn.getInputStream());
response = convertStreamToString(in);
in.close();
} catch (MalformedURLException e) {
Log.e(TAG, "MalformedURLException: " + e.getMessage());
} catch (ProtocolException e) {
Log.e(TAG, "ProtocolException: " + e.getMessage());
} catch (IOException e) {
Log.e(TAG, "IOException: " + e.getMessage());
} catch (Exception e) {
Log.e(TAG, "Exception: " + e.getMessage());
}
return response;
}
private String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line;
try {
while ((line = reader.readLine()) != null) {
sb.append(line).append('\n');
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}
To run it.
new Execute().execute;

Parsing Integer from JSON not working [duplicate]

This question already has answers here:
How do I parse JSON in Android? [duplicate]
(3 answers)
Closed 6 years ago.
I am attempting to make an app in android studio that gets live currency rates, so I decided to use a JSON to do this. I am currently able to print out the entire JSON as a string, however I would like to be able to set the TextView to the USD conversion rate, however it doesn't work. The TextView does not change. Any help would be greatly appreciated.
public class Converter extends AppCompatActivity {
TextView txtJson;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_converter);
txtJson = (TextView) findViewById(R.id.tvJsonItem);
new JsonTask().execute("https://openexchangerates.org/api/latest.json?app_id=870447ebb4d94379972250a3bdaed73f");
}
private class JsonTask extends AsyncTask<String, String, String> {
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line + "\n");
Log.d("Response: ", "> " + line);
}
return buffer.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
public void onPostExecute(String result) {
super.onPostExecute(result);
try {
JSONObject jObject = new JSONObject(result);
int USD = jObject.getInt("USD");
String strUSD = Integer.toString(USD);
txtJson.setText(strUSD);
} catch (JSONException e) {
e.printStackTrace();
}
}
}}
You need to get the "rates" object before you can access the "USD" value
Also, it's not an integer. It's a double
getJSONObject("rates").getDouble("USD")

android get url from edit text and use it in rest api to upload data

Here is my android rest request code but the where i get the url from edit text using its id but "getString" gets flagged(can't be resolved). Please help
class RESTRequest
{
//final String ADD_STROKE_URL = "";
final String ADD_STROKE_URL = new String[]{ getString(R.id.buttonUploadURL)};
public Boolean success = null;
private JSONObject params;
private String strokeId;
private HashSet<Point> localPoints;
private StrokeManagerCallback callback;
public static String encode(Object x) {
try {
return URLEncoder.encode(String.valueOf(x),"UTF-8");
} catch (UnsupportedEncodingException e) {
return(String.valueOf(x));
}
}
public RESTRequest(JSONObject params,String strokeId,Set<Point> points,StrokeManagerCallback callback)
{
this.params = params;
this.strokeId = strokeId;
this.localPoints = new HashSet<Point>();
this.localPoints.addAll(points);
this.callback = callback;
new ExecuteREST().execute();
}
private class ExecuteREST extends AsyncTask<Void, Void, String>
{
protected String doInBackground(Void ...arg0)
{
/* Build URL query */
StringBuffer local = new StringBuffer(ADD_STROKE_URL);
if(params != null)
{
local.append("?");
Iterator<?> k = params.keys();
while(k.hasNext()){
try {
String key = (String) k.next();
Object value = params.get(key);
local.append(encode(key));
local.append("=");
local.append(encode(value));
if(k.hasNext()){
local.append("&");
}
}
catch (JSONException e) {e.printStackTrace();}
}
}
HttpURLConnection urlConn = null;
StringBuffer response = new StringBuffer("error");
try
{
URL url = new URL(local.toString());
urlConn = (HttpURLConnection) url.openConnection();
urlConn.setRequestMethod("GET");
urlConn.setDoInput(true);
urlConn.setUseCaches(false);
urlConn.setRequestProperty("Content-Type", "application/json");
urlConn.connect();
//Get Response
InputStream is = urlConn.getInputStream();
BufferedReader rd = new BufferedReader(newInputStreamReader(is));
String line;
response = new StringBuffer();
try{
while((line = rd.readLine()) != null) {
response.append(line);
}
}
finally{
if(urlConn != null){
urlConn.disconnect();
urlConn = null;
}
if(rd != null){
rd.close();
rd = null;
}
}
if(callback != null){
callback.onSuccess(strokeId, localPoints);
}
} catch (ConnectException e) {
callback.onFailure(strokeId, localPoints);
} catch (UnknownHostException e) {
callback.onFailure(strokeId, localPoints);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (EOFException e) {
response = new StringBuffer("No response from server");
} catch (IOException e) {
e.printStackTrace();
} catch (RuntimeException e) {
e.printStackTrace();
}
finally{
if(urlConn != null){
urlConn.disconnect();
}
}
return response.toString();
}
}
you can get String Resources like this
Resources res = context.getResources();
final String ADD_STROKE_URL = new String[]{ res.getString(R.id.buttonUploadURL)};
and now you can pass that url in AcycncTask class like this
public RESTRequest(JSONObject params,String
strokeId,Set<Point>points,StrokeManagerCallback callback){
this.params = params;
this.strokeId = strokeId;
this.localPoints = new HashSet<Point>();
this.localPoints.addAll(points);
this.callback = callback;
new ExecuteREST(/*Pass url here that you will get in doInBackground method */)
.execute();
}
private class ExecuteREST extends AsyncTask<String, Void, String>{
protected String doInBackground(String ...arg0){
//get your url in arg0 variable
StringBuffer local = new StringBuffer(arg0[0]);
.
.
.
//Rest of yours ...

How Can add a JSON Data to Array in JAVA

I have an project and I'm trying to convey to data from JSON Array to normal array. But I could not this. Can you help me if you know which and where code I add to in my project. My Main Activity file is here
public class MainActivity extends AppCompatActivity {
private TextView tvData;
private String[] stringArray;
protected ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout mDrawerLayout;
private NavigationView mNavigationView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvData = (TextView)findViewById(R.id.bilgi);
setupToolbar();
initNavigationDrawer();
new JSONTask().execute("http://192.168.1.36:8080/urunler/kategori_goster.php");
}
public class JSONTask 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();
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 finalJson = buffer.toString();
JSONObject parentObject = new JSONObject(finalJson);
JSONArray parrentArray = parentObject.getJSONArray("uyelerimiz");
StringBuffer finalBufferedData = new StringBuffer();
for(int i=0;i<parrentArray.length(); i++)
{
JSONObject finalObject = parrentArray.getJSONObject(i);
String year = finalObject.getString("kategori_adi");
finalBufferedData.append(year + " \n");
}
return finalBufferedData.toString();
} 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);
tvData.setText(result);
}
}
JSON is working whitout any problem. I want to add my JSON data to my " private String[] stringArray;"
Here is how the JSON is formatted:
{
"uyelerimiz":[
{
"kategori_adi":"Bilgisayar"
},
{
"kategori_adi" ‌​:"Cep Telefonu"
},
{
"kategori_adi":"Saglik"
},
{
"kategori_adi":"Kirtas‌​iye"
}
]
}
private String[] parseJson(String response){
try {
JSONObject lJsonObject = new JSONObject(response);
JSONArray lJsonArray = lJsonObject.getJSONArray("uyelerimiz");
String[] lResult = new String[lJsonArray.length()];
for (int index = 0;index<lJsonArray.length();index++){
lResult[index] = lJsonArray.getJSONObject(index).getString("kategori_adi");
}
return lResult;
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}

doInBackground throws NullPointerException for no reason

In here the code with BufferedReaderand line = reader.readLine() works
public class WeatherService extends AsyncTask<TaskParams, Void, String> {
private WeatherServiceCallback callback;
private Exception exception;
public WeatherService(WeatherServiceCallback callback) {
this.callback = callback;
}
#Override
protected String doInBackground(TaskParams... params) {
try {
URL url = new URL("http://api.openweathermap.org/data/2.5/weather?lat=" +
params[0].getLat() + "&lon=" + params[0].getLon() +
"&units=" + TaskParams.getUnits() +
"&type=" + TaskParams.getAccuracy() + "&lang=" + TaskParams.getLanguage() +
"&appid=10660a09a9fb335d72f576f7aa1bbe5b");
URLConnection connection = url.openConnection();
InputStream inputStream = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder builder = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
return builder.toString();
} catch (MalformedURLException e) {
exception = e;
} catch (IOException e) {
exception = e;
}
return null;
}
#Override
protected void onPostExecute(String s)
{
if (s == null && exception != null)
{
callback.serviceFailure(exception);
return;
}
try
{
JSONObject data = new JSONObject(s);
Parameters parameters = new Parameters();
parameters.poopulate(data);
callback.serviceSuccess(parameters);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
I copy-pasted code to other class since it has very similar functionality and now for no reason I'm getting NullPointerException in while ((line = reader.readLine()) != null) and I have no idea why since as I said it's copy-pasted (I only changed URL and object returned if serivce succeeds)
public class PollutionService extends AsyncTask<TaskParams, Void, String>
{
private PollutionServiceCallback callback;
private Exception exception;
private URLConnection connection;
private InputStream inputStream;
private InputStreamReader streamReader;
private BufferedReader reader;
public PollutionService(PollutionServiceCallback callback) {
this.callback = callback;
}
#Override
protected String doInBackground(TaskParams... params) {
try
{
URL url = new URL("http://api.openweathermap.org/pollution/v1/co/" + params[0].getLat() +
"," + params[0].getLon() + "/current.json?&appid=10660a09a9fb335d72f576f7aa1bbe5b");
try
{
connection = url.openConnection();
}
catch (IOException e)
{
exception = new Exception("Connection error");
}
try
{
inputStream = connection.getInputStream();
}
catch (IOException e)
{
exception = new Exception("Input stream error");
}
try
{
streamReader = new InputStreamReader(inputStream);
}
catch (NullPointerException e)
{
exception = new Exception("Input stream reader error");
}
try
{
reader = new BufferedReader(streamReader);
}
catch (NullPointerException e)
{
exception = new Exception("Buffered reader error");
}
StringBuilder builder = new StringBuilder();
String line;
try
{
while ((line = reader.readLine()) != null)
{
builder.append(line);
}
}
catch (IOException e)
{
exception = e;
}
return builder.toString();
}
catch (MalformedURLException e)
{
exception = e;
}
return null;
}
#Override
protected void onPostExecute(String s)
{
if (s == null && exception != null)
{
callback.pollutionServiceFailure(exception);
return;
}
try
{
JSONObject data = new JSONObject(s);
PollutionParameters parameters = new PollutionParameters();
parameters.poopulate(data);
callback.pollutionServiceSuccess(parameters);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Any clue?
EDIT
This is rewritten code for PollutionActivity. Callback function serviceFailure prints now the URL address on my phone's screen
public class PollutionService extends AsyncTask<TaskParams, Void, String>
{
private PollutionServiceCallback callback;
private Exception exception;
public PollutionService(PollutionServiceCallback callback) {
this.callback = callback;
}
#Override
protected String doInBackground(TaskParams... params) {
try
{
URL url = new URL("http://api.openweathermap.org/pollution/v1/co/" + params[0].getLat() +
"," + params[0].getLon() + "/current.json?&appid=10660a09a9fb335d72f576f7aa1bbe5b");
URLConnection connection = url.openConnection();
InputStream inputStream = connection.getInputStream();
InputStreamReader streamReader = new InputStreamReader(inputStream);
BufferedReader reader = new BufferedReader(streamReader);
StringBuilder builder = new StringBuilder();
String line;
try
{
while ((line = reader.readLine()) != null)
{
builder.append(line);
}
}
catch (IOException e)
{
exception = e;
}
return builder.toString();
}
catch (MalformedURLException e)
{
exception = e;
}
catch (IOException e)
{
exception = e;
}
return null;
}
#Override
protected void onPostExecute(String s)
{
if (s == null && exception != null)
{
callback.pollutionServiceFailure(exception);
return;
}
try
{
JSONObject data = new JSONObject(s);
PollutionParameters parameters = new PollutionParameters();
parameters.poopulate(data);
callback.pollutionServiceSuccess(parameters);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Debugging showed me that code jumps to exception after
InputStream inputStream = connection.getInputStream();
If you are getting NPE for reader then it means that reader is not getting initialized and going null.Your code is getting crash at line 23 and 89. So I believe that the problem is right at the start somewhere and not at the point itself, may be some object is going null like connection.Since line number is not displayed here.Check null pointer for every object like if (connection!=null). Since the initial data is coming null,maybe input stream or some other data,hence your reader object is not getting initialized.Also check if you are getting value for every object in debug.

Categories

Resources