I am trying to get a int that is inside a JSONObject and put it in a String Array, but i only can put it in a simple String.
This is what inside the JSONObject {"codigo":2,"nome":"Teste 2"}
That is the code that i can pass the int from codigo to a simple String
String informacao;
String code;
String name[];
ListView listView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
informacao = intent.getStringExtra("INFO");
try{
JSONObject jo = new JSONObject(informacao);
for (int i = 0; i < jo.length(); i++){
Log.i("ENTROU", "entrou");
code = jo.getString("codigo").toString();
Log.i("CODE!!!", code.toString());
}
} catch (JSONException e){
Log.i("ERRO", e.toString());
}
Logcat from it
2020-03-20 09:48:48.046 23998-23998/br.com.ifractal.Stou I/ENTROU: entrou
2020-03-20 09:48:48.046 23998-23998/br.com.ifractal.Stou I/CODE!!!: 2
2020-03-20 09:48:48.046 23998-23998/br.com.ifractal.Stou I/ENTROU: entrou
2020-03-20 09:48:48.046 23998-23998/br.com.ifractal.Stou I/CODE!!!: 2
Now when i try to put it in a String Array
String informacao;
String code[];
String name[];
ListView listView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
informacao = intent.getStringExtra("INFO");
try{
JSONObject jo = new JSONObject(informacao);
for (int i = 0; i < jo.length(); i++){
Log.i("ENTROU", "entrou");
code[i] = jo.getString("codigo").toString();
Log.i("CODE!!!", code[i].toString());
}
} catch (JSONException e){
Log.i("ERRO", e.toString());
}
Logcat from that
2020-03-20 09:56:25.195 25695-25695/br.com.ifractal.Stou I/ENTROU: entrou
You are not setting the length of the array. It doesn't dynamically increase like in JavaScript. If you initialize the array like so: String code[] = new String[10]; you should be able to set its elements.
Related
I have an app that is supposed to read a json file and inset its contents into a list view, I know this question was asked tons of times here but I can't understand why it's not working. I managed to narrow my problem to 1 line so far, JSONObject object = new JSONObject(readJSON());. This is all of my code:
public class MainActivity extends AppCompatActivity {
ListView listView;
ArrayList<Post> arrayList;
private static final String TAG = "MyActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.lvPosts);
arrayList = new ArrayList<>();
try {
JSONObject object = new JSONObject(readJSON());
JSONArray array = object.getJSONArray("data");
for (int i = 0; i < array.length(); i++) {
JSONObject jsonObject = array.getJSONObject(i);
String productName = jsonObject.getString("productName");
String locationName = jsonObject.getString("locationName");
String price = jsonObject.getString("price");
String date = jsonObject.getString("date");
String description = jsonObject.getString("description");
String comment = jsonObject.getString("comment");
Log.i(TAG, price);
Post post = new Post();
post.setItemName(productName);
post.setLocationName(locationName);
post.setPrice(price);
post.setDate(date);
post.setDescription(description);
post.setExistingComment(comment);
arrayList.add(post);
}
} catch (JSONException e) {
e.printStackTrace();
}
PostAdapter adapter = new PostAdapter(this, arrayList);
listView.setAdapter(adapter);
}
public String readJSON() {
String json = null;
try {
// Opening data.json file
InputStream inputStream = getAssets().open("MOCK_DATA.json");
int size = inputStream.available();
byte[] buffer = new byte[size];
// read values in the byte array
inputStream.read(buffer);
inputStream.close();
// convert byte to string
json = new String(buffer, "UTF-8");
} catch (IOException e) {
e.printStackTrace();
return null;
}
return json;
}
}
My problem is that once I run the app my listView will remain empty and wont be populated with data.
if you are using java version >jdk1.7 then I would recommend you use Files class from "java.nio.file" package . you can easily read JSON file in a single line code.
public String readJSON() {
String jsontext="";
try{
jsontext= new String(Files.readAllBytes(Paths.get("<file path>"),StandardCharset.UTF_8);
}
catch(Exception ex){
ex.printStackTrace();
}
return jsontext;
}
after that you can use JSONObject to parse string like below:---
JSONObject object = new JSONObject(readJSON());
I am working on an android application. In this application, I have to retrieve data from a web service and put it in a listview, but it is not retrieving anything. I don't know what I am doing wrong here. Maybe someone can help me with this.
Webservice: http://10.247.240.53/kas/lampen.php
Mainactivity:
`
public class MainActivity extends AppCompatActivity {
ListView listView;
ArrayAdapter<String> adapter;
String[] data;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = findViewById(R.id.listview);
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().permitNetwork().build());
getData();
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(MainActivity.this, Showdata.class);
intent.putExtra("teeltbed", listView.getItemAtPosition(position).toString());
startActivity(intent);
}
});
}
private void getData()
{
String getData = null;
String dbResult = "empty";
dbConnect database = new dbConnect(this);
try{
String query = "SELECT * FROM Lamp";
getData = "?query=" + URLEncoder.encode(query, "UTF-8");
String link = "http://10.247.240.53/kas/lampen.php";
dbResult = database.execute(link).get();
}
catch (Exception e){
}
try{
JSONArray ja = new JSONArray(dbResult);
JSONObject jo = null;
data = new String[ja.length()];
for (int i = 0; i < ja.length(); i++)
{
jo = ja.getJSONObject(i);
data[i] = jo.getString("teeltbed");
}
adapter = new ArrayAdapter<String>(this, R.layout.layout_list, R.id.list_item, data);
listView.setAdapter(adapter);
}
catch (Exception e)
{
e.printStackTrace();
}
}
}`
I tried many ways but I got blank layout.I changed lots of lines but the result is always the same. Should I rewrite the code and try something different. I followed some videos on youtube but nobody has the proper solution.I don't think it is caused because array got null result. Anybody knows what might be wrong:
AirportTransportActivity
public class AirportTransportActivity extends AppCompatActivity {
ListView listView;
ArrayAdapter<String> adapter;
String[] data = new String[0];
JSONObject jsonObject = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_airport_transport);
//Get airport details
Intent intent = getIntent();
String getairport = intent.getStringExtra("airport");
final TextView textViewAirport = (TextView) findViewById(R.id.tvairport);
textViewAirport.setText(getairport);
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().permitNetwork().build());
//List view setup
listView = (ListView) findViewById(R.id.lvairport);
//Get airport transport
new RetrieveTask().execute();
//Adapter
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, data);
listView.setAdapter(adapter);
}
private class RetrieveTask extends AsyncTask<Void, Void, String> {
#Override
protected String doInBackground(Void... voids) {
String strUrl = "http://my database";
URL url = null;
StringBuffer sb = new StringBuffer();
try {
url = new URL(strUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream iStream = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(iStream));
String line = "";
while ((line = reader.readLine()) != null) {
sb.append(line);
}
reader.close();
iStream.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return sb.toString();
}
#Override
protected void onPostExecute(String result) {
try {
JSONArray jsonArray = new JSONArray(result);
data = new String[jsonArray.length()];
for (int i = 0; i < jsonArray.length(); i++) {
jsonObject = jsonArray.getJSONObject(i);
data[i] = jsonObject.getString("airporttransportname");
}
} catch (JSONException e) {
e.printStackTrace();
}
adapter.notifyDataSetChanged();
}
}
}
In your original post you have set the adapter before you have added the data. But I also suspect that you are having issues with:
String[] data = new String[0];
So I changed it to
ArrayList<String> data = new ArrayList<>();
I also changed your AsyncTask a bit. Now you can do most of your parsing in the background thread. When the doInBackground is successful just notify the adapter of the changes in onPostExecute.
You will also need to check if the ArrayList<String> fits to your Adapter class. If not just change it as needed.
Do this instead:
public class AirportTransportActivity extends AppCompatActivity {
private static final String TAG = AirportTransportActivity.class.getSimpleName();
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_airport_transport);
//Get airport details
Intent intent = getIntent();
String getairport = intent.getStringExtra("airport");
final TextView textViewAirport = (TextView) findViewById(R.id.tvairport);
textViewAirport.setText(getairport);
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().permitNetwork().build());
//List view setup
listView = (ListView) findViewById(R.id.lvairport);
//Get airport transport
new RetrieveTask().execute();
}
private class RetrieveTask extends AsyncTask<Void, Void, String> {
#Override
protected String doInBackground(Void... voids) {
String strUrl = "http://my database";
URL url = null;
StringBuffer sb = new StringBuffer();
try {
url = new URL(strUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream iStream = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(iStream));
String line = "";
while ((line = reader.readLine()) != null) {
sb.append(line);
}
reader.close();
iStream.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return toString();
}
#Override
protected void onPostExecute(String result) {
if(result.isEmpty()) return;
try{
ArrayList<String> data = new ArrayList<>();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, data);
JSONArray jsonArray = new JSONArray(result);
int len = jsonArray.length();
Log.e(TAG, "Lenth of json array = " + len)
for (int i = 0; i < len; i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
// I add the optString variation just in case the data is corrupt
String s = jsonObject.optString("airporttransportname", "?");
data.add(s);
}
listView.setAdapter(adapter);
}
catch(JSONException e){
e.printStackTrace();
}
}
}
Disclaimer I did this in a text editor and wasn't able to count on "auto-correct" for some of the syntax or method names--so you will need to check it.
There are some other things I would change in your code, but I wanted to leave it as close to the original as I could.
You're setting the data array and calling notifyDataSetChanged() before your async task has a chance to finish. You need to set your adapter and notifyDataSetChanged() from within the onPostExecute() method in your async task.
Just to be clear, when you call asyncTask.execute(), it starts the async task and then immediately keeps executing the rest of the code. So when you set your data array in your list view adapter, the asyncTask hasn't even finished and your array items are still null.
No need to change anything just add adapter.notifyDataSetChanged(); after storing all values into your array
Remove this line adapter.notifyDataSetChanged();in Oncreate ,You
have to use notifyDataSetChanged() when your arraylist values is getting
changed.
#Override
protected void onPostExecute(String result) {
try {
JSONArray jsonArray = new JSONArray(result);
data = new String[jsonArray.length()];
for (int i = 0; i < jsonArray.length(); i++) {
jsonObject = jsonArray.getJSONObject(i);
data[i] = jsonObject.getString("airporttransportname");
}
} catch (JSONException e) {
e.printStackTrace();
}
adapter.notifyDataSetChanged();
}
Here I'm using the following code to create a string current[] using for loop:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_imageactivity);
Intent intent = getIntent();
String jsonArray = intent.getStringExtra("jsonArray");
try {
JSONArray array = new JSONArray(jsonArray);
for (int i = 0; i < array.length(); i++) {
JSONObject obj = array.getJSONObject(i);
String current_name[] = { obj.getString("current_name") }; // array
}
} catch (JSONException e) {
e.printStackTrace();
}
}
// Log.e(TAG,"VALUES" + Arrays.toString(current_name));
Now I want to call this current_name[] outside OnCreate or some other method. By using this code I can't Log outside OnCreate. So please help me to solve this issue. Answers will be appreciated.
Declare the array as a member of the activity and in the onCreate initialize it only
try {
JSONArray array = new JSONArray(jsonArray);
for (int i = 0; i < array.length(); i++) {
JSONObject obj = array.getJSONObject(i);
current_name[i] = obj.getString("current_name");
}
} catch (JSONException e) {
e.printStackTrace();
}
try this one.
String current_name[] = {};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_imageactivity);
Intent intent = getIntent();
String jsonArray = intent.getStringExtra("jsonArray");
try {
JSONArray array = new JSONArray(jsonArray);
for (int i = 0; i < array.length(); i++) {
JSONObject obj = array.getJSONObject(i);
current_name[i] =obj.getString("current_name"); // array
}
} catch (JSONException e) {
e.printStackTrace();
}
}
Now you can access String out of oncreate.
I parsed json to adapt for my autocompleteTextView. I tried to match the value parsed by my json object with the value entered by user.
But some where i am failing. please help me in matching these values.
i have to match the string(acity) that is entered by user with my parsed json value stored in responseList.
This is how i am trying.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
new HttpGetTask().execute();
Button shwBtn = (Button) findViewById(R.id.showBtn);
shwBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
AutoCompleteTextView city1 = (AutoCompleteTextView) findViewById(R.id.autoCity);
EditText area1 = (EditText) findViewById(R.id.edArea);
String aCity = city1.getText().toString().trim();
String aArea = area1.getText().toString().trim();
//here i have to match acity with all the values in responseList before sending it to next activity
Intent myInt = new Intent(getBaseContext(),
Map1Activity.class);
String city = city1.getText().toString();
String area = area1.getText().toString();
myInt.putExtra("city", city);
myInt.putExtra("area", area);
startActivity(myInt);
}
});
}
private class HttpGetTask extends AsyncTask<Void, Void, String> {
String URL = "xyzz.cities.json?app_id=test";
AndroidHttpClient mClient = AndroidHttpClient.newInstance("");
#Override
protected String doInBackground(Void... params) {
// http stuff
return null;
}
#Override
protected void onPostExecute(String result) {
try {
JSONArray json = new JSONArray(result);
//getting my response(cities)
Log.v("ResponseCity", result);
final List<String> responseList = new ArrayList<String>();
for (int i = 0; i < json.length(); i++) {
final JSONObject e = json.getJSONObject(i);
String name = e.getString("name");
//Adding all values to a stringList
responseList.add(name);
ArrayAdapter<String> adapter;
adapter = new ArrayAdapter<String>(SearchActivity.this,
android.R.layout.simple_dropdown_item_1line,
responseList);
AutoCompleteTextView textView = (AutoCompleteTextView) findViewById(R.id.autoCity);
textView.setAdapter(adapter);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (null != mClient)
mClient.close();
}
}
So lets assume you need to match a certain city before you intent to a map :
private final List<String> responseList;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
new HttpGetTask().execute();
Button shwBtn = (Button) findViewById(R.id.showBtn);
shwBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
AutoCompleteTextView city1 = (AutoCompleteTextView) findViewById(R.id.autoCity);
EditText area1 = (EditText) findViewById(R.id.edArea);
String aCity = city1.getText().toString().trim();
String aArea = area1.getText().toString().trim();
//here i have to match acity with all the values in responseList before sending it to next activity
for(int i=0; i<responseList.size(); i++) {
if(responseList.get(i).equals(aCity)) {
Intent myInt = new Intent(getBaseContext(),
Map1Activity.class);
String city = city1.getText().toString();
String area = area1.getText().toString();
myInt.putExtra("city", city);
myInt.putExtra("area", area);
startActivity(myInt);
}
}
}
});
}
private class HttpGetTask extends AsyncTask<Void, Void, String> {
String URL = "xyzz.cities.json?app_id=test";
AndroidHttpClient mClient = AndroidHttpClient.newInstance("");
#Override
protected String doInBackground(Void... params) {
// http stuff
return null;
}
#Override
protected void onPostExecute(String result) {
try {
JSONArray json = new JSONArray(result);
//getting my response(cities)
Log.v("ResponseCity", result);
responseList = new ArrayList<String>();
for (int i = 0; i < json.length(); i++) {
final JSONObject e = json.getJSONObject(i);
String name = e.getString("name");
//Adding all values to a stringList
responseList.add(name);
ArrayAdapter<String> adapter;
adapter = new ArrayAdapter<String>(SearchActivity.this,
android.R.layout.simple_dropdown_item_1line,
responseList);
AutoCompleteTextView textView = (AutoCompleteTextView) findViewById(R.id.autoCity);
textView.setAdapter(adapter);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (null != mClient)
mClient.close();
}
}
It should be something like that if I didnt guess your intent wrongly.