This question already has answers here:
Asynctask: pass two or more values from doInBackground to onPostExecute
(5 answers)
Closed 5 years ago.
I have problem with parsing my JSON Object to multiple textview.
I have a TextView1, TextView2 and TextView3.
I would like to download data from: "max", "min" and "average" and synch data with .settext in TextView1, TextView2 and TextView3
My JSON looks: {"max":15.6,"min":14.05,"average":14.55}
My code below:
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();
Log.d("Login attempt", connection.toString());
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);
String maxPrice = parentObject.getString("max");
return maxPrice;
} 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;
}
onPostExecute:
protected void onPostExecute (String result){
super.onPostExecute(result);
maxPrice.setText(result);
I can't add more String and synch in other TextView. That's work only for one TextView. I can't synch multiple TextView. Can you help me?
1) Return your finalJson from doInBackground
2) getString & setText in onPostExecute
JSONObject parentObject = new JSONObject(result);
String maxPrice = parentObject.getString("max");
String minPrice = parentObject.getString("min");
String avg = parentObject.getString("average");
tvMaxPrice.setText(maxPrice);
tvMinPrice.setText(minPrice);
tvAvg.setText(avg);
you have two option.
1st option
return your whole json string like
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String finalJson = buffer.toString();
return finalJson;
then process your json on your onPostExecute like
protected void onPostExecute (String result){
super.onPostExecute(result);
JSONObject parentObject = new JSONObject(result);
String maxPrice = parentObject.getString("max");
maxPrice.setText(result);
String minPrice = parentObject.getString("min");
minPrice.setText(result);
String avgPrice = parentObject.getString("avg");
avgPrice.setText(result);
}
or
2nd option is
You have to try like this
String result = "";
String maxPrice = parentObject.getString("max");
String avgPrice = parentObject.getString("avg");
String minPrice = parentObject.getString("min");
result = maxPrice+","+avgPrice+","+minPrice;
return result;
then split it on your onPostExecute
protected void onPostExecute (String result){
super.onPostExecute(result);
String[] separated = result.split(",");
maxPrice.setText(separated[0]);
minPrice.setText(separated[2]);
avgPrice.setText(separated[1]);
}
Related
class GetData extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
HttpURLConnection urlConnection = null;
String result = "";
try {
URL url = new URL("http://192.168.0.100/index.php?kod=1eba7936&mode=1");
urlConnection = (HttpURLConnection) url.openConnection();
int code = urlConnection.getResponseCode();
if(code==200){
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
if (in != null) {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in));
String line = "";
while ((line = bufferedReader.readLine()) != null)
result += line;
}
in.close();
}
return result;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
finally {
urlConnection.disconnect();
}
return result;
}
#Override
protected void onPostExecute(String result) {
System.out.println(result);
super.onPostExecute(result);
}
}
I got such class, its work great exept i cannot catch variable as it returns void. The result its single integer value. And System.out.println(result) display proper value on console.
I call function from MainActivity with
new GetData().execute();
My goal is to have result from GetData as integer variable in MainActivity.
I made new class with public string
public class Data {
public static String data;
}
In onPostExecute i add:
Data.data = result.toString();
And now i can use Data.data as string whetever i want.
I want wrote an API in php for using it in my android app. In the php side I do this for return info in an array
echo json_encode($array)
result of this code is like this, see online result in this link:
{"value":[{"id":"1","name":"kufta","meal":"1","photo_id":"","explanation":"xoshmazas","foodtime":"0000-00-0000:00:00"},{"id":"2","name":"\r\nAsh","meal":"2","photo_id":"","explanation":"sdfdsfsdfdsfdsfsdf","foodtime":"2017-06-26 14:00:00"},{"id":"3","name":"kabab","meal":"3","photo_id":"","explanation":"kabab kheili khoshmaze ast","foodtime":"2017-06-29 00:00:00"}]}
but in java side when I load this, app crash but when I use this json string in this site. Android app works fine
my java code for reading the url content
public class WebService {
private String connectToServer(String address, String requestMethod) {
try {
URL url = new URL(address);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod(requestMethod);
return inputStreamToString(httpURLConnection.getInputStream());
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private String inputStreamToString(InputStream inputStream) {
StringBuilder stringBuilder = new StringBuilder();
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String nextLine;
while ((nextLine = reader.readLine()) != null) {
stringBuilder.append(nextLine);
}
} catch (IOException e) {
e.printStackTrace();
}
return stringBuilder.toString();
}
line 23 : public List<FoodModel> getFoods(){ <-----------Error is here
String response = connectToServer("http://mtg1376.gigfa.com/api/food?day=All","GET");
if(response != null){
List<FoodModel> foodList = new ArrayList<😠);
try{
JSONObject mainObject = new JSONObject(response);
JSONArray foodArray = mainObject.getJSONArray("value");
for(int i = 0 ; i< foodArray.length();i++){
JSONObject foodObject = foodArray.getJSONObject(i);
FoodModel foodModel = new FoodModel();
foodModel.id = foodObject.getString("id");
foodModel.name = foodObject.getString("name");
foodModel.meal = foodObject.getString("meal");
foodModel.photo_id = foodObject.getString("photo_id");
foodModel.explanation = foodObject.getString("explanation");
foodModel.foodtime=foodObject.getString("foodtime");
foodList.add(foodModel);
}
return foodList;
} catch (JSONException e) {
e.printStackTrace();
}
}
return null; }
}
java error log : https://ibb.co/hQneXk
whats the problem?
I've been following a tutorial which provided an example website to use in the json request, however when i put in my own website to scrape data from, nothing happens.
Here is my code;
private TextView tvData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvData = (TextView) findViewById(R.id.tvJsonItem);
new JSONTask().execute("http://jsonparsing.parseapp.com/jsonData/moviesDemoItem.txt");
}
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 parentArray = parentObject.getJSONArray("movies");
JSONObject finalObject = parentArray.getJSONObject(0);
String ChampionName = finalObject.getString("movie");
String mostGames = finalObject.getString("year");
return ChampionName + mostGames;
} 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);
}
}
}
Screen of when it works on left and screen when it doesnt work on right.
So yeah, this is what i know i have to change
new JSONTask().execute("http://api.champion.gg/champion/Ekko");
and
JSONObject parentObject = new JSONObject(finalJson);
JSONArray parentArray = parentObject.getJSONArray("WHAT DO I PUT HERE");
JSONObject finalObject = parentArray.getJSONObject(0);
String ChampionName = finalObject.getString("WHAT DO I PUT HERE");
String mostGames = finalObject.getString("WHAT DO I PUT HERE");
From this URL - http://api.champion.gg/champion/Ekko/ , i want to get lets say the first two fields "key":"Ekko","role":"Top", so if anyone could give me a hand, that would be great!
According to the JSON returned form your link http://api.champion.gg/champion/Ekko/
You have to start to parse your string response as JSONArray
JSONArray parentObject = new JSONArray(finalJson);
then start to loop through this array to get JSONObject
JSONObject jsonObject = parentObject.getJSONObject(yourLoopIndex);
Inside each JSONObject you can get any value. by using the key in the original JSON string.
Everything seems to be fine except for the JSON exception error.
Here it is specifically: org.json.JSONException:
Value username of type `java.lang.String` cannot be converted to `JSONObject`.
There are a number of other flags that I can check in logcat and everything seems pretty good except that. I think the problem is that I need to convert the String encodedStr into a JSON object and return it to ASYNC TASK.
private class AsyncDataClass extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
//Use HashMap, it works similar to NameValuePair
Map<String, String> dataToSend = new HashMap<>();
dataToSend.put("username", params[1]);
dataToSend.put("password", params[2]);
//Server Communication part - it's relatively long but uses standard methods
//Encoded String - we will have to encode string by our custom method (Very easy)
String encodedStr = getEncodedData(dataToSend);
//Will be used if we want to read some data from server
BufferedReader reader = null;
//Connection Handling
try {
//Converting address String to URL
URL url = new URL(serverUrl);
//Opening the connection (Not setting or using CONNECTION_TIMEOUT)
HttpURLConnection con = (HttpURLConnection) url.openConnection();
//Post Method
con.setRequestMethod("POST");
//To enable inputting values using POST method
//(Basically, after this we can write the dataToSend to the body of POST method)
con.setDoOutput(true);
OutputStreamWriter writer = new OutputStreamWriter(con.getOutputStream());
//Writing dataToSend to outputstreamwriter
writer.write(encodedStr);
//Sending the data to the server - This much is enough to send data to server
//But to read the response of the server, you will have to implement the procedure below
writer.flush();
//Data Read Procedure - Basically reading the data comming line by line
StringBuilder sb = new StringBuilder();
reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String line;
while ((line = reader.readLine()) != null) { //Read till there is something available
sb.append(line + "\n"); //Reading and saving line by line - not all at once
}
line = sb.toString();//Saving complete data received in string, you can do it differently
//Just check to the values received in Logcat
Log.i("custom_check", "The values received in the store part are as follows:");
Log.i("custom_check", line);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close(); //Closing the
} catch (IOException e) {
e.printStackTrace();
}
}
}
//Same return null, but if you want to return the read string (stored in line)
//then change the parameters of AsyncTask and return that type, by converting
//the string - to say JSON or user in your case
**strong text**return encodedStr;**strong text**
**strong text**HERE IS THE PROBLEM I BELIEVE.
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
System.out.println("Resulted Value: " + result);
if (result.equals("") || result == null) {
Toast.makeText(MainActivity.this, "Server connection failed", Toast.LENGTH_LONG).show();
return;
}
int jsonResult = returnParsedJsonObject(result);
if (jsonResult == 0) {
Toast.makeText(MainActivity.this, "Invalid username or password", Toast.LENGTH_LONG).show();
return;
}
if (jsonResult == 1) {
Intent intent = new Intent(MainActivity.this, LoginActivity.class);
intent.putExtra("USERNAME", enteredUsername);
intent.putExtra("MESSAGE", "You have been successfully login");
startActivity(intent);
}
}
private int returnParsedJsonObject(String result) {
JSONObject resultObject = null;
int returnedResult = 0;
try {
resultObject = new JSONObject(result);
returnedResult = resultObject.getInt("success");
} catch (JSONException e) {
e.printStackTrace();
}
return returnedResult;
}
}
private StringBuilder inputStreamToString(InputStream is) {
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
try {
while ((rLine = br.readLine()) != null) {
answer.append(rLine);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return answer;
}
//************getEncodedData*****************//
private String getEncodedData(Map<String,String> data) {
StringBuilder sb = new StringBuilder();
for(String key : data.keySet()) {
String value = null;
try {
value = URLEncoder.encode(data.get(key), "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
if(sb.length()>0)
sb.append("&");
sb.append(key + "=" + value);
}
return sb.toString();
}`enter code here`
i would like to write data in an external mysql database with my android app.
this class works for that:
public class SendingData extends AppCompatActivity {
Intent intent = null;
private class LoadingDataURL extends AsyncTask<String, String, JSONArray> {
#Override
protected JSONArray doInBackground(String... params) {
URL url;
HttpURLConnection urlConnection = null;
JSONArray response = new JSONArray();
try {
url = new URL(params[0]);
urlConnection = (HttpURLConnection) url.openConnection();
int responseCode = urlConnection.getResponseCode();
String responseString = readStream(urlConnection.getInputStream());
intent = new Intent(SendingData.this, Overview.class);
startActivity(intent);
response = new JSONArray(responseString);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (urlConnection != null)
urlConnection.disconnect();
}
return response;
}
private String readStream(InputStream in) {
BufferedReader reader = null;
StringBuffer response = new StringBuffer();
try {
reader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
String line = "";
while ((line = reader.readLine()) != null) {
response.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return response.toString();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.loading_data);
String firstname = "Max";
String secondname= "Mustermann";
LoadingDataURL client = new LoadingDataURL();
client.execute("https://domain.com/index.php?"+
"fristname="+fristname+
"&secondname="+secondname);
}
}
My Problem is, that if in my strings (fristname, secondname) is an & or ? or any special characters, the entry will not be save correctly.
any ideas? :)
Use the URLEncoder class.
Try this please
String fn = URLEncoder.encode(fristname, "utf-8");
String sn = URLEncoder.encode(secondname, "utf-8");
LoadingDataURL client = new LoadingDataURL();
client.execute("https://domain.com/index.php?"+
"fristname=" + fn + "&secondname=" + sn);
Note: Don't encode the full url, just the parameter values.