Android - put data into array in asynctask - java

I got a question that I don't know how to solve.
I am trying to achieve putting the 'question' and 'answer' into the 2D Array, but it cannot put the data into the 2D array in the asyncTask.
I am expecting I can put the 'question' and 'answer' that get in JSON Object into the 2D array. And then use the array in OnCreate method.
public class MainActivity extends Activity {
String[][] array = new String[10][4];
private TextView tvData;
int qnum = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
String quest;
String ans;
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new JSONTask().execute("http://itdmoodle.hung0530.com/ptms/questions_ws.php");
Button btnNext = (Button) findViewById(R.id.btnNext);
tvData = (TextView) findViewById(R.id.textView);
for(int i=0;i<10;i++){
int z = i+1;
array[i][0] = String.valueOf(z);
}
quest = array[0][1];
ans = array[0][2];
tvData.setText(quest);
btnNext.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
}
});
}
public class JSONTask extends AsyncTask<String, String, String>{
#Override
protected String doInBackground(String... params) {
HttpURLConnection conn = null;
BufferedReader reader = null;
try{
URL url = new URL(params[0]);
conn = (HttpURLConnection) url.openConnection();
conn.connect();
InputStream stream = conn.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line ="";
while((line = reader.readLine()) != null){
buffer.append(line);
}
String Json = buffer.toString();
JSONObject jsonObject = new JSONObject(Json);
JSONArray jsonArray = jsonObject.getJSONArray("Questions");
StringBuffer bufferQues = new StringBuffer();
StringBuffer bufferAns = new StringBuffer();
for(int i=0;i<jsonArray.length();i++) {
JSONObject otherJson = jsonArray.getJSONObject(i);
String question = otherJson.getString("question");
String answer = otherJson.getString("answer");
bufferQues.append(question);
bufferAns.append(answer);
array[i][1] = bufferQues.toString();
array[i][2] = bufferAns.toString();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally{
if(conn != null){
conn.disconnect();
}
try{
if(reader != null){
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String result){
super.onPostExecute(result);
}
}
}

Asynctask executes asynchronously. It allows you to perform long running operations on a background thread(doInBackground is run on a seperate thread than main thread) and use the results to perform operations on main thread(onPostExecute runs on main thread).
What you want is to perform the operation on your 2D array in onPostExecute and not in onCreate.

Related

Hello i am trying to display json data from url into listview. Nothing is displayed though

Url
private static String JSON_URL ="https://run.mocky.io/v3/aff3f637-d04f-45c0-b002-09be1a143784";
ArrayList<HashMap<String,String>> friendsList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
friendsList= new ArrayList<>();
lv = findViewById(R.id.listview);
GetData getData= new GetData();
getData.execute();
}
Getting the data
public class GetData extends AsyncTask<String, String, String>{
#Override
protected String doInBackground(String... strings) {
String current = "";
try {
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL(JSON_URL);
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader isr = new InputStreamReader(in);
int data = isr.read();
while (data != -1) {
current += (char) data;
data = isr.read();
}
return current;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
} catch (Exception e){
e.printStackTrace();
}
return current;
}
Displaying the data
#Override
protected void onPostExecute(String s) {
try{
JSONObject jsonObject= new JSONObject(s);
JSONArray jsonArray = jsonObject.getJSONArray("Friends"); //name of array
for(int i = 0; i <jsonArray.length();i++)
{
JSONObject jsonObject1 = jsonArray.getJSONObject(i);
namey=jsonObject.getString("name");
age= jsonObject1.getString("age");
//Hashmap
HashMap<String, String> friends = new HashMap<>();
friends.put("name",namey);
friends.put("age", age);
friendsList.add(friends);
}
} catch (JSONException e) {
e.printStackTrace();
}
//Displaying the results
ListAdapter adapter = new SimpleAdapter(
MainActivity.this,
friendsList,
R.layout.row_layout,
new String[]{"name","age"},
new int[]{R.id.textView, R.id.textView2});
lv.setAdapter(adapter);
}
}
}
It doesnt display anything and i believe it has something to do with the url, but i am not quite sure so please help and thank you in advance
Your mocky JSON from https://run.mocky.io/v3/aff3f637-d04f-45c0-b002-09be1a143784 is wrong format, you need to remove the last character

Problem in parsing data from Json Google Places API to recyclerView

I would like to show users a list of bar near by them, without map. I have tried by PlaceLikelihoods, it works fine but I can not put any restriction on the types of place found and it shows a map.
So I searched by URL, but the Try / Catch always leads to the exception, the toast found there shows the good result but the list of recyclerview is not filled.
I found a similar problem that said to move the notifyDataSetChanged(), I have done it.
I find APIs and parsing very complicated to master so it's probably a stupid mistake but it's been 2 weeks and I have not yet succeeded.
Thanks for reading.
public class TestMap extends AppCompatActivity {
// CONNECTION_TIMEOUT and READ_TIMEOUT are in milliseconds
public static final int CONNECTION_TIMEOUT = 10000;
public static final int READ_TIMEOUT = 15000;
private LocListAdapter mAdapter;
private EmptyStateRecyclerView mLocRecView;
private ArrayList<LocListUser> data;
private double longitudeUser;
private double latitudeUser;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_loc);
data = new ArrayList<>();
mAdapter = new LocListAdapter(data, TestMap.this);
mLocRecView = findViewById(R.id.locRecView);
mLocRecView.setItemAnimator(new DefaultItemAnimator());
mLocRecView.setLayoutManager(new LinearLayoutManager(TestMap.this));
mLocRecView.setHasFixedSize(true);
//data.clear();
mLocRecView.setAdapter(mAdapter);
mLocRecView.clearStateDisplays();
longitudeUser = getIntent().getDoubleExtra("long", 151.2106085);
latitudeUser = getIntent().getDoubleExtra("lat", -33.8523341);
new AsyncFetch().execute();
}
private class AsyncFetch extends AsyncTask<String, String, String> {
ProgressDialog pdLoading = new ProgressDialog(TestMap.this);
HttpURLConnection conn;
URL url = null;
#Override
protected void onPreExecute() {
super.onPreExecute();
pdLoading.setMessage("\tLoading...");
pdLoading.setCancelable(false);
pdLoading.show();
}
#Override
protected String doInBackground(String... params) {
try {
StringBuilder sb;
sb = new StringBuilder("https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
sb.append("location=").append(latitudeUser).append(",").append(longitudeUser);
sb.append("&radius=5000");
sb.append("&types=" + "bar");
sb.append("&key=API_KEY");
url = new URL(String.valueOf(sb));
} catch (MalformedURLException e) {
e.printStackTrace();
return e.toString();
}
try {
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(READ_TIMEOUT);
conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.setRequestMethod("GET");
conn.setDoOutput(true);
} catch (IOException e1) {
e1.printStackTrace();
return e1.toString();
}
try {
int response_code = conn.getResponseCode();
if (response_code == HttpURLConnection.HTTP_OK) {
InputStream input = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input, StandardCharsets.UTF_8));
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
// Pass data to onPostExecute method
return (result.toString());
} else {
return ("unsuccessful");
}
} catch (IOException e) {
e.printStackTrace();
return e.toString();
} finally {
conn.disconnect();
}
}
#Override
protected void onPostExecute(String result) {
pdLoading.dismiss();
try {
JSONArray jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
LocListUser locList = new LocListUser();
locList.setAddress(json_data.getString("vicinity"));
locList.setId(json_data.getString("reference"));
locList.setName(json_data.getString("place_name"));
locList.setLat(json_data.getJSONObject("geometry").getJSONObject("location").getString("lat"));
locList.setLon(json_data.getJSONObject("geometry").getJSONObject("location").getString("lng"));
locList.setType(json_data.getString("types"));
locList.setLatUser(latitudeUser);
locList.setLonUser(longitudeUser);
data.add(locList);
mAdapter.notifyDataSetChanged();
}
//mAdapter.notifyDataSetChanged();
mLocRecView.invokeState(EmptyStateRecyclerView.STATE_OK);
} catch (JSONException e) { //e.toString()
e.printStackTrace();
}
}
}
}
you are using hardcoded string
JSONArray jArray = new JSONArray("results");
you have to use
JSONArray jArray = new JSONArray(result);

Is it possible that the array map is too little for contain about 2000 items?

In my code i had caught data from a JSON file,
I executed the program, it stopped but didn't crash.
i've tried to change json file. I found one that is Smaller than the first one and so the program works.
this JSON file is made of data o premier legue(England) and contain 3 mainly data, the name, a key and a code of the squads.
public class MainActivity extends AppCompatActivity {
private ProgressDialog caric;
private String TAG = MainActivity.class.getSimpleName();
public ArrayMap<Integer, Valori> ArrayDati = new ArrayMap<>();
Button buttonProg;
TextView textViewProg;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonProg = (Button) findViewById(R.id.button);
textViewProg = (TextView) findViewById(R.id.textView);
buttonProg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new JsonCLASS().execute("https://raw.githubusercontent.com/openfootball/football.json/master/2015-16/en.1.clubs.json");
}
});
}
private class JsonCLASS extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
caric = new ProgressDialog(MainActivity.this);
caric.setMessage("Please wait");
caric.setCancelable(false);
caric.show();
}
#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 + "\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
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
JSONObject jsonObject = new JSONObject(result);
JSONArray Arr = new JSONArray(jsonObject.getString("clubs"));
for (int i = 0; i < Arr.length(); i++){
JSONObject jsonPart = Arr.getJSONObject(i);
ArrayDati.put(i,new Valori( jsonPart.getString("key"), jsonPart.getString("name"), jsonPart.getString("code")));
textViewProg.setText(textViewProg.getText()+"key : "+ ArrayDati.get(i).Key
+"\n"+textViewProg.getText()+"name : "+ ArrayDati.get(i).Name
+"\n"+textViewProg.getText()+"code : "+ ArrayDati.get(i).Code );
}
} catch (Exception e ){
e.printStackTrace();
}
if (caric.isShowing()) {
caric.dismiss();
}
}
}
}
And a class to pass the data
public class Valori {
String Key;
String Name;
String Code;
public Valori(String key, String name, String code) {
this.Key = key;
this.Name = name;
this.Code = code;
}
}
With this code the application stops but it doesn't close.

Empty string when reading data sent from server

I'm having trouble with this code. The variable result should be filled from the response of the server, but for any reason, it keeps returning an empty string.
This is the entire code:
public class FragmentRally extends Fragment {
public FragmentRally() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_fragment_rally, container, false);
new AsyncFetch().execute();
return rootView;
}
// CONNECTION_TIMEOUT and READ_TIMEOUT are in milliseconds
public static final int CONNECTION_TIMEOUT = 10000;
public static final int READ_TIMEOUT = 15000;
private RecyclerView vistaRallye;
private AdapterRallye adaptadorRallye;
private class AsyncFetch extends AsyncTask<String, String, String> {
ProgressDialog pdLoading = new ProgressDialog(getActivity());
HttpURLConnection conn;
URL url = null;
#Override
protected void onPreExecute() {
super.onPreExecute();
//this method will be running on UI thread
pdLoading.setMessage("\tCarregant...");
pdLoading.setCancelable(false);
pdLoading.show();
}
#Override
protected String doInBackground(String... params) {
try {
// Enter URL address where your json file resides
// Even you can make call to php file which returns json data
url = new URL("http://www.rallyecat.esy.es/Obtenir_events.php");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return e.toString();
}
try {
// Setup HttpURLConnection class to send and receive data from php and mysql
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(READ_TIMEOUT);
conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.setRequestMethod("GET");
// setDoOutput to true as we recieve data from json file
conn.setDoOutput(true);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
return e1.toString();
}
try {
int response_code = conn.getResponseCode();
// Check if successful connection made
if (response_code == HttpURLConnection.HTTP_OK) {
// Read data sent from server
InputStream input = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
// Pass data to onPostExecute method
return (result.toString());
} else {
return ("No hi ha connexió a internet.");
}
} catch (IOException e) {
e.printStackTrace();
return e.toString();
} finally {
conn.disconnect();
}
}
#Override
protected void onPostExecute(String result) {
//this method will be running on UI thread
pdLoading.dismiss();
List<DataRallye> data = new ArrayList<>();
pdLoading.dismiss();
try {
JSONArray jArray = new JSONArray(result);
// Extract data from json and store into ArrayList as class objects
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
DataRallye dadesrallye = new DataRallye();
dadesrallye.RallyeNom = json_data.getString("nom");
dadesrallye.RallyeTipus = json_data.getString("tipus");
dadesrallye.RallyeDataI = json_data.getString("datai");
dadesrallye.RallyeDataF = json_data.getString("dataf");
dadesrallye.RallyeCiutat = json_data.getString("ciutat");
dadesrallye.RallyeOrganitzacio = json_data.getString("organitzacio");
dadesrallye.RallyeFoto = json_data.getString("foto");
data.add(dadesrallye);
}
// Setup and Handover data to recyclerview
vistaRallye = (RecyclerView) getView().findViewById(R.id.llistarallyes);
adaptadorRallye = new AdapterRallye(getActivity(), data);
vistaRallye.setAdapter(adaptadorRallye);
vistaRallye.setLayoutManager(new LinearLayoutManager(getActivity()));
} catch (JSONException e) {
Toast.makeText(getActivity(), e.toString(), Toast.LENGTH_LONG).show();
}
}
}
}
The problem appears here:
// Read data sent from server
InputStream input = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
// Pass data to onPostExecute method
return (result.toString());
This variable, RESULT is passed here, where I do the JSON Parse. But as it is empty, it goes directly to the catch exception:
#Override
protected void onPostExecute(String result) {
//this method will be running on UI thread
pdLoading.dismiss();
List<DataRallye> data = new ArrayList<>();
pdLoading.dismiss();
try {
JSONArray jArray = new JSONArray(result);
// Extract data from json and store into ArrayList as class objects
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
DataRallye dadesrallye = new DataRallye();
dadesrallye.RallyeNom = json_data.getString("nom");
dadesrallye.RallyeTipus = json_data.getString("tipus");
dadesrallye.RallyeDataI = json_data.getString("datai");
dadesrallye.RallyeDataF = json_data.getString("dataf");
dadesrallye.RallyeCiutat = json_data.getString("ciutat");
dadesrallye.RallyeOrganitzacio = json_data.getString("organitzacio");
dadesrallye.RallyeFoto = json_data.getString("foto");
data.add(dadesrallye);
}
// Setup and Handover data to recyclerview
vistaRallye = (RecyclerView) getView().findViewById(R.id.llistarallyes);
adaptadorRallye = new AdapterRallye(getActivity(), data);
vistaRallye.setAdapter(adaptadorRallye);
vistaRallye.setLayoutManager(new LinearLayoutManager(getActivity()));
} catch (JSONException e) {
Toast.makeText(getActivity(), e.toString(), Toast.LENGTH_LONG).show();
}
Here is the JSON generated from a PHP file on our website:
[{"id_rally":"1","nom":"45e rallye costa brava","tipus":"velocitat i regularitat","datai":"2017-06-20","dataf":"2017-06-22","ciutat":"Girona","organitzacio":"rallyclassics ","foto":"brava.png"},{"id_rally":"2","nom":"26e rallye igualada","tipus":"velocitat","datai":"2017-08-13","dataf":"2017-08-16","ciutat":"Igualada","organitzacio":"ecb org","foto":"igualada.png"}]
conn.setDoOutput(true);.
Remove that line. As you will not write data to the outputstream.
result.append(line);
That should be
result.append(line) + "\n";
For 'GET' connections set
conn.setDoOutput(false);
setDoOutput(true) is used for POST and PUT requests.

Trying to troubleshoot a JSON with an array within an array

I'm trying to troubleshoot my code, which has a array within an array, and then I want to retrieve all of the ID values inside it
private TextView tvData;
private ImageView imgtest;
String ChampionName;
String ChampionNameInLowerCase;
String item2;
String item3;
String Booked;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvData = (TextView) findViewById(R.id.tvJsonItem);
imgtest = (ImageView) findViewById(R.id.imageView);
// http://api.champion.gg/champion/Ekko/
new JSONTask().execute("http://api.champion.gg/champion/Ekko/");
}
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();
JSONArray jsonarray = new JSONArray(finalJson);
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject finalObject = jsonarray.getJSONObject(i);
ChampionName = finalObject.getString("key");
String role = finalObject.getString("role");
String items = finalObject.getString("items");
JSONObject ItemArray = new JSONObject(items);
item2 = ItemArray.getString("mostGames");
JSONObject ItemArray2 = new JSONObject(item2);
item3 = ItemArray2.getString("items");
JSONArray jsonarray2 = new JSONArray(item3);
for (int j=0;j<jsonarray2.length();j++) {
JSONObject finalObject2 = jsonarray.getJSONObject(j);
Booked = finalObject2.getString("id");
}
return ChampionName + role + item3 + Booked;
}
} 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);
ChampionNameInLowerCase = ChampionName.toLowerCase().replaceAll("'", "");;
int id = getResources().getIdentifier("com.example.kripzy.url:drawable/" + ChampionNameInLowerCase+"_square_0", null ,null);
imgtest.setImageResource(id);
}
}
}
And then more closely the code up for question is this section;
JSONArray jsonarray2 = new JSONArray(item3);
for (int j=0;j<jsonarray2.length();j++) {
JSONObject finalObject2 = jsonarray.getJSONObject(j);
Booked = finalObject2.getString("id");
}
return ChampionName + role + item3 + Booked;
}
When the code directly above is added, it gives an error
org.json.JSONException: No value for id
When I delete that small snippet of code, the code produces
The problem is here Booked = finalObject2.getString("id"); use Booked = finalObject2.getInt("id");
and by the way you can use
JSONObject finalObject2 = jsonarray.getJSONObject(jsonarray2.length()-1); instead the the for (int j=0;j<jsonarray2.length();j++)
In the for-loop where you iterate over jsonarray2 you access jsonarray instead of jsonarray2 to get your JSONObject.

Categories

Resources