Need help to retrieve all the data to listview - java

I'm trying to make an android application that can read data from a database. but when I try to display some rows in the listview, only the bottom row of the code that I make is displayed.
this is my code for MainActivity
public class MainActivity extends AppCompatActivity {
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = findViewById(R.id.listView);
getJSON("http://192.168.137.234/librenms/getdata.php");
}
private void getJSON(final String urlWebService) {
class GetJSON extends AsyncTask<Void, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
try {
loadIntoListView(s);
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
protected String doInBackground(Void... voids) {
try {
URL url = new URL(urlWebService);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
StringBuilder sb = new StringBuilder();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String json;
while ((json = bufferedReader.readLine()) !=null) {
sb.append(json).append("\n");
}
return sb.toString().trim();
} catch (Exception e) {
return null;
}
}
}
GetJSON getJSON = new GetJSON();
getJSON.execute();
}
private void loadIntoListView(String json) throws JSONException {
JSONArray jsonArray = new JSONArray(json);
String[] alerts = new String[jsonArray.length()];
this is the part to showing the atribute on listview
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
alerts[i] = object.getString("Rule ID");
alerts[i] = object.getString("Device ID");
alerts[i] = object.getString("Time logged");
}
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, alerts);
listView.setAdapter(arrayAdapter);
}
}

Related

Content from web-site won't display in my logcat

I am trying to download content of some random web content to my Logcat. I already did this many time but now I am getting only 2020-05-17 13:24:20.850 24632-24632/com.example.jsondownload I/RezultatĀ URLa:: { and nothing else.Content is some random JSON small sample and I want to show it in my logcat, and nothing else.
I added internet permission.
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String string = "https://api.openweathermap.org/data/2.5/weather?q=London,uk&appid=6...3";
DownloadAsync downloadAsync = new DownloadAsync();
downloadAsync.execute(string);
}
public static class DownloadAsync extends AsyncTask<String,Void,String> {
#Override
protected String doInBackground(String... strings) {
StringBuilder rezultat = new StringBuilder();
URL url;
HttpURLConnection httpURLConnection;
try {
url = new URL(strings[0]);
httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
int podaci = inputStreamReader.read();
while (podaci!=-1){
char trenutnoSlovoKojeSeCita = (char) podaci;
rezultat.append(trenutnoSlovoKojeSeCita);
podaci = inputStream.read();
}
return rezultat.toString();
}
catch (Exception e){
e.printStackTrace();
return "Neuspesno";
}
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Log.i("Rezultat URLa: ",s);
}
}
}
I find a solution: I added BufferReader:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String string = "https://api.openweathermap.org/data/2.5/weather?q=Belgrade&appid=6c5022949de1b8e8448bc7232238dcf3";
DownloadAsync downloadAsync = new DownloadAsync();
downloadAsync.execute(string);
}
public static class DownloadAsync extends AsyncTask<String,Void,String> {
#Override
protected String doInBackground(String... strings) {
StringBuilder rezultat = new StringBuilder();
URL url;
HttpURLConnection httpURLConnection;
try {
url = new URL(strings[0]);
httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, Charset.forName("UTF-8"));
BufferedReader reader = new BufferedReader(inputStreamReader);
String line = reader.readLine();
while (line!=null){
rezultat.append(line);
line = reader.readLine();
}
return rezultat.toString();
}
catch (Exception e){
e.printStackTrace();
return "Neuspesno " ;
}
}
#Override
protected void onPostExecute(String rezultat) {
super.onPostExecute(rezultat);
try {
JSONObject jsonObject = new JSONObject(rezultat);
String weatherInfo = jsonObject.getString("weather");
JSONArray arr = new JSONArray(weatherInfo);
for (int i = 0; i < arr.length();i++){
JSONObject jsonObject1 = arr.getJSONObject(i);
String main = jsonObject1.getString("main");
String desc = jsonObject1.getString("description");
Log.i("main: ",main);
Log.i("description: ",desc);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}

JSON ListView filter not working

So I've got a project to make a simple job board app. I've retrieved my JSON data and have it displaying on my app but I want to be able to use a SearchView filter but I don't know how to access my SimpleAdapter from outside of an inner-class
Here is my code:
public class jobcategories extends Activity{
private TextView jobData;
private ProgressDialog myprocessingdialog;
ArrayAdapter<String> adapter;
ArrayList<HashMap<String, String>> jobList;
private ListView lv;
private SearchView sv;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.jobcategories);
myprocessingdialog = new ProgressDialog(this);
jobList = new ArrayList<>();
lv = (ListView) findViewById(R.id.list);
sv = (SearchView) findViewById(R.id.search);
sv.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String text) {
return false;
}
#Override
public boolean onQueryTextChange(String text) {
adapter.getFilter().filter(text);
return false;
}
});
new JSONTask().execute("https://apidata.com");
}
public class JSONTask extends AsyncTask<String,String, String>{
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
//Showing Progress dialogue
myprocessingdialog.setTitle("Please Wait..");
myprocessingdialog.setMessage("Loading");
myprocessingdialog.setCancelable(false);
myprocessingdialog.setIndeterminate(false);
myprocessingdialog.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);
}
String finalJson = buffer.toString();
JSONArray parentObject = new JSONArray(finalJson);
for (int i=0; i < parentObject.length(); i++) {
JSONObject job = parentObject.getJSONObject(i);
String JobTitle = job.getString("title");
String JobLocation = job.getString("location");
String finalTitle = JobTitle + " in " + JobLocation;
String JobCompany = "advert by "+job.getString("company");
String JobDescription = job.getString("description");
String JobApply = "How to Apply: " + job.getString("apply");
HashMap<String, String> jobs = new HashMap<>();
jobs.put("title", finalTitle);
jobs.put("company", JobCompany);
jobs.put("description", JobDescription);
jobs.put("apply", JobApply);
jobList.add(jobs);
}
}catch (MalformedURLException e){
Toast.makeText(getApplicationContext(), "Error...the job server is down..." + e.toString(), Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "error parsing..." + e.toString(), Toast.LENGTH_LONG).show();
} finally {
if(connection != null) {
connection.disconnect();
}
try {
if(reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String results) {
super.onPostExecute(results);
myprocessingdialog.cancel();
ListAdapter adapter = new SimpleAdapter(
jobcategories.this, jobList,
R.layout.list_item, new String[]{"title", "company", "description", "apply"},
new int[]{R.id.title, R.id.company, R.id.description, R.id.apply});
lv.setAdapter(adapter);
}
}
}
Any help would be appreciated, am pretty new to android so if there is a better way for me to filter the data then I am open to changing the code.
Create an interface called OnJsonResultListener like so:
public interface OnJsonResultListener {
void onResult(String result);
}
Then make your Activity/Fragment implement that interface and do whatever with your simple adapter and the result from there. Then make the AsyncTask take a OnJsonResultListener in the constructor. Then in the onPostExecute method, call listener.onResult(results);
This is a simple way of making a callback.

Getting and Parsing JSON in the same Activity (Null Pointer Exception)

I want to get and parse json in the same activity but when I try to do this I get
Null Pointer Exception
I think I am getting this error because background task is slower than my code.
In My main activity:
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
new BackgroundTask().execute();
categoryAdapter = new CategoryAdapter(this,R.layout.row_layout);//I am sure,there is no problem in Category Adapter
listView = (ListView) findViewById(R.id.listview);
listView.setAdapter(categoryAdapter);
String id,kategori;
try {
Log.d("jsonstring",JSON_STRING); //I am getting error here JSON_STRING causes null pointer.
jsonObject = new JSONObject(JSON_STRING);
int count = 0;
jsonArray = jsonObject.getJSONArray("server_response");
while(count<jsonArray.length()){
JSONObject JO = jsonArray.getJSONObject(count);
id = JO.getString("id");
kategori = JO.getString("kategori");
Categories categories = new Categories(id,kategori);
categoryAdapter.add(categories);
count++;
}
} catch (JSONException e) {
e.printStackTrace();
}
listView.setOnItemClickListener(new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Categories contact = (Categories) listView.getItemAtPosition(position);
// Log.d("position",""+position);
// Log.d("id",""+id);
Log.d("id",contact.getId());
Log.d("kategori",contact.getKategori());
}
});
Background Task class:
class BackgroundTask extends AsyncTask<Void,Void,String> {
String json_url= "exampleurl"; // I am sure, here is correct!
#Override
protected String doInBackground(Void... voids) {
try {
URL url = new URL(json_url);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder stringBuilder = new StringBuilder();
while ((json_string = bufferedReader.readLine())!=null){
stringBuilder.append(json_string+"\n");
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return stringBuilder.toString().trim();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public BackgroundTask() {
super();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(String result) {
// TextView textView = (TextView)findViewById(R.id.textView);
// textView.setText(result);
JSON_STRING = result;
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}
I have Categories class with id and kategori attributes.
Finally How can I solve this problem? In fact I can parse after getting JSON.

Unable to access string from class

I want to show string from another string in my MainActivity, but the string is getting printed in console. Here is my code:
public class MainActivity extends AppCompatActivity {
Button start;
public TextView showText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
showText= (TextView)findViewById(R.id.textView);
start = (Button)findViewById(R.id.button);
start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RetrieveFeedTask click1 = new RetrieveFeedTask();
click1.execute();
showText.setText(click1.getString());
}
});
}
}
And the class:
class RetrieveFeedTask extends AsyncTask<Void, Void, String> {
static final String API_URL = "http://numbersapi.com/random/trivia?json";
private Exception exception;
public String finalString;
protected void onPreExecute() { }
protected String doInBackground(Void... urls) {
try {
URL url = new URL(API_URL );
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuilder stringBuilder = new StringBuilder();
while ((finalString = bufferedReader.readLine()) != null) {
stringBuilder.append(finalString).append("\n");
}
bufferedReader.close();
return stringBuilder.toString();
}
finally{
urlConnection.disconnect();
}
}
catch(Exception e) {
Log.e("ERROR", e.getMessage(), e);
return null;
}
}
protected void onPostExecute(String response) {
if(response == null) {
response = "THERE WAS AN ERROR";
}
try {
JSONObject object = (JSONObject) new JSONTokener(response).nextValue();
finalString = object.getString("text");
Log.i("Here",finalString);
} catch (JSONException e) {
}
}
public String getString() {
return this.finalString;
}
}
You require the finalString before it's populated with your data. the onPostExecute is executed after the doInBackground so you should pass your text view to your task and set it's value in the onPostExecute
public TextView showText;
public RetrieveFeedTask(TextView showText) { this.showText = showText; }
protected void onPostExecute(String response) {
if(response == null) {
response = "THERE WAS AN ERROR";
}
try {
JSONObject object = (JSONObject) new JSONTokener(response).nextValue();
finalString = object.getString("text");
showText.setText(finalString ); // add this
Log.i("Here",finalString);
} catch (JSONException e) {
}
}
The problem is that showText.setText(click1.getString()); of your activity is called earlier than finalString = object.getString("text"); of your task.
Solution:
Create an interface:
public interface DataCallback {
void onNewData(String data);
}
and implement it in your activity:
public class MainActivity extends ... implements DataCallback
public void onNewData(String data) {
showText.setText(data);
}
Pass the interface to your asynctask when you create it:
RetrieveFeedTask click1 = new RetrieveFeedTask(this);
Call the interface inside the task in onPostExecute() to notify the activity that there is new data:
JSONObject object = (JSONObject) new JSONTokener(response).nextValue();
finalString = object.getString("text");
callback.onNewData(finalString);

Async json parsing- What am i doing wrong?

I have been trying to work on an app in which after clicking ,a new activity opens up and loads the data from the url.
Here is the new activity code
ProgressDialog dialog;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
}
private class MyTask extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
dialog.setMessage("Processing");
dialog.setIndeterminate(true);
dialog.show();
dialog.getWindow().setLayout(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
try {
JSONObject jsonObject = new JSONObject();
String url = " http://www.trailermag.com/tsappapis/?request=featuredAdList";
JSONArray trailersJSON = jsonObject.getJSONArray(url);
for (int i = 0; i < trailersJSON.length(); i++) {
Trail aTrail = new Trail();
JSONObject contactObject = trailersJSON.getJSONObject(i);
aTrail.id = contactObject.getString(V_Id);
aTrail.image = contactObject.getString(V_Image);
aTrail.title = contactObject.getString(V_Title);
aTrail.price = contactObject.getString(V_Price);
webData.add(aTrail);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
if (dialog.isShowing()) {
System.out.println("IN POST EXE");
dialog.dismiss();
}
}
}
Once try and replace this code with your code this will work and i have tested it.
JSONArray mJsonArray = new JSONArray(response);
for (int i = 0; i < mJsonArray.length(); i++) {
JSONObject mJsonObject = mJsonArray.getJSONObject(i);
String idStr = mJsonObject.getString("id");
String imageStr = mJsonObject.getString("image");
String titleStr = mJsonObject.getString("title");
String priceStr = mJsonObject.getString("price");
}
Happeee...Programming....

Categories

Resources