how to clear listview and add the new listview - java

If I clear the list view, the listview will gone.The list view will fetch data from the for loop.
Workarounds:
Putting setdaylist.clear() inside the any loop will clear the all listview and display only one list item.
Setting it at the top of method will erase all the listview, any solution?
Code:
public void onDataGotOnline(JSONObject response) {
DateTime today = new DateTime().withTimeAtStartOfDay();
DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
try {
JSONArray currentData = response.getJSONArray("list");
// setdaylist.clear();
for (int i = 1; i < 5; i++) {
DateTime tomorow = today.plusDays(i).withTimeAtStartOfDay();
String dtStr = fmt.print(tomorow);
int info = 0;
for(; info<currentData.length();info++ ){
JSONObject managedata = currentData.getJSONObject(info);
String time= managedata.getString("dt_txt");
if(time.equals(dtStr)){
int getResult=info+8;
double[] arrayAverageTemp = new double[8];
double[] arrayMaxTemp = new double[8];
double[] arrayMinTemp = new double[8];
int[] arrayWheaterId = new int[8];
for (int a = info; a < getResult; a++) {
JSONObject datalist = currentData.getJSONObject(i);
JSONArray weatherdata = datalist.getJSONArray("weather");
JSONObject weatherdata2 = weatherdata.getJSONObject(weatherdata.length() - 1);
int id = weatherdata2.getInt("id");
JSONObject weather = datalist.getJSONObject("main");
double avg_temp = weather.getDouble("temp");
double max_temp = weather.getDouble("temp_max");
double min_temp = weather.getDouble("temp_min");
arrayWheaterId[a-info]=id;
arrayAverageTemp[a-info]=avg_temp;
arrayMaxTemp[a-info]=max_temp;
arrayMinTemp[a-info]=min_temp;
}
ManageData manageData = new ManageData();
double max = manageData.findMax(arrayMaxTemp);
double min = manageData.findMin(arrayMinTemp);
WheatherData day = new WheatherData();
day.setDay("sunday");
// int image = convert.covertImage(icon);
day.setImage(R.drawable.ic_image_01d);
day.setDescrption("asdasd");
day.setAvgTemp("14 °c");
day.setMaxTemp(max+ "°c");
day.setMinTemp(min+ "°c");
setdaylist.add(day);
adapter.notifyDataSetChanged();
// findMax(arrayMaxTemp);
//findMin(arrayMinTemp);
//findID(arrayWheaterId);
//findaverage(arrayAverageTemp);
}
}
}
}
catch (JSONException e){
}
}

From the discussion above.
Issue was due to the caching problem in Android studio.
Cleaning Project and Building it removes the existing cache.
By which the setdaylist before the for loop shown below works as expected.
public void onDataGotOnline(JSONObject response) {
...
try {
...
setdaylist.clear();
for (int i = 1; i < 5; i++) {
...
for(; info<currentData.length();info++ ){
...
if(time.equals(dtStr)){
...
setdaylist.add(day);
...
}
}
}
}
catch (JSONException e){}
}

Related

How to apply for loop on first n vlalues of arraylist

I have an arraylist in which I have ESSID, BSSID, Strenght of access Point on first three indexes, and from Index 4 to 6 I have again ESSID, BSSID, Strength of another AccessPoint. I want to store this list in database like first three values save in one row of table. and next three values save in 2nd row of table.
String[] namesArr = new String[arrayList2.size()]; //conver arraylist to array
for (int j = 0; j < arrayList2.size(); j++){
namesArr[j] = arrayList2.get(j);
int length = namesArr[j].length();
for (int k = 0; k < length; k += 3) {
ssid = namesArr[k];
bssid = namesArr[k + 1];
rssid = namesArr[k + 2];
}
insertValues(this);
}
public void insertValues(View.OnClickListener view){
SendData send = new SendData(this);
send.execute(bssid,ssid,rssid);}
I have made a class to store this data in database that works fine.
public class SendData extends AsyncTask<String, Void, String> {
AlertDialog dialog;
Context context;
public SendData(Context context) {
this.context = context;
}
#Override
protected void onPreExecute() {
dialog = new AlertDialog.Builder(context).create();
dialog.setTitle("Message");
}
#Override
protected void onPostExecute(String s) {
dialog.setMessage(s);
dialog.show();
}
#Override
protected String doInBackground(String... voids) {
String data = "";
String result = "";
String MAC = voids[0];
String Name = voids[1];
String Strength = voids[2];
String con_Str = "http://10.5.48.129/Webapi/accesspoints_data/create.php";
try{
URL url = new URL(con_Str);
HttpURLConnection http = (HttpURLConnection) url.openConnection();
http.setRequestMethod("POST");
http.setDoInput(true);
http.setDoOutput(true);
OutputStream out_Stream = http.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out_Stream, "UTF-8"));
JSONObject obj = new JSONObject();
try {
obj.put("BSSID", MAC);
obj.put("ESSID", Name);
obj.put("RSSID", Strength);
} catch (JSONException e) {
e.printStackTrace();
}
data = obj.toString();
writer.write(data);
writer.flush();
writer.close();
out_Stream.close();
InputStream in_Stream = http.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in_Stream, "ISO-8859-1"));
String line = "";
while ((line = reader.readLine()) != null)
{
result += line;
}
reader.close();
in_Stream.close();
http.disconnect();
return result;
} catch (MalformedURLException e){
result = e.getMessage();
} catch (IOException e){
result = e.getMessage();
}
return result;
}
}
SendData class is perfectly working but problem is with for loop.
I think this is result that you are expecting :
List<String> arrayList2 = new ArrayList<>();
arrayList2.add("1");
arrayList2.add("2");
arrayList2.add("3");
arrayList2.add("4");
arrayList2.add("5");
arrayList2.add("6");
arrayList2.add("6");
arrayList2.add("7");
arrayList2.add("8");
arrayList2.add("9");
arrayList2.add("10");
List<String[]> sarrayList = new ArrayList<>();
String[] arr = new String[3];
int i = 0;
for (int j = 0; j < arrayList2.size(); j++)
{
arr[i] = arrayList2.get(j);
i++;
if((j+1)%3==0)
{
sarrayList.add(arr);
i = 0;
arr = new String[3];
}
}
for(String [] sa:sarrayList)
{
for(String s:sa)
{
System.out.println(s);
}
System.out.println("=========");
}
This might not be the most efficient way of doing it. But it splits the ArrayList in to String arrays of length=3 and stores them in a new ArrayList named sarrayList
I would advise to use a datastructure to hold the record. See the code below this is a small example how you could do it
ArrayList<Record> records;
for (int i = 2; i < inputArrayList.size(); i = i + 3){
string ssid = namesArr.get(i - 2);
string bssid = namesArr.get(i - 1);
string rssid = namesArr.get(i);
records.add(new Record(ssid, bssid, rssid));
}
class Record{
string ssid;
string bssid;
string rssid;
// Constructor...
// Getter and setter to be implemented...
}
ok from what i understand you want to divide the arraylist each 3 elements thats how you do it with streams and it will return an a collection of arraylists each one has 3 elements
final int chunkSize = 3;
final AtomicInteger counter = new AtomicInteger();
//arrayList here us your array list
final Collection<List<String>> result = arrayList.stream()
.collect(Collectors.groupingBy(it -> counter.getAndIncrement() / chunkSize))
.values();
and mentioning supermar10 answer you code make a class to map the strings to it like that
class Record{
string ssid;
string bssid;
string rssid;
Record(String ssid,String bssid,String rssid){
this.ssid=ssid;
this.bssid=bssid;
this.rssid=rssid;
}
}
now you have a class to map to now save the records in a list of Record
create a a list in the main class
static List<Record> lists=new ArrayList<>();
then map the data like that
result.stream().forEach(nowList -> saveRecord(nowList));
and thats the save method
static void saveRecord(List<String> list){
lists.add(new Record(list.get(0),list.get(1),list.get(2)));
}
I have simplified it to one loop and also modified insertValues so that it takes 3 more parameters. This
int size = arrayList2.size();
for (int j = 0; j < size; j += 3) {
if (size - j < 3 ) {
break;
}
String ssid = arrayList2.get(j);
String bssid = arrayList2.get(j + 1);
String rssid = arrayList2.get(j + 2);
insertValues(this, ssid, bssid, rssid);
}
if one the other hand ssid and so on are class variables the inside of the loop can be changed to
ssid = arrayList2.get(j);
bssid = arrayList2.get(j + 1);
rssid = arrayList2.get(j + 2);
insertValues();

How to display Object array in JTable?

This is my code which I am using but when I am trying to print dataArray object, then data is not show in JTable. Which model properties of table to print Object array values can used and how?
public class ShowAddressForm extends javax.swing.JFrame {
Object data[][];
Object dataArray[][];
int count = 0;
String st;
public ShowAddressForm(String fname , String str) {
super(fname);
st = str;
initComponents();
fillTable();
}
public void fillTable()
{
int count = 0;
String str;
try
{
BufferedReader br = new BufferedReader(new FileReader("D:\\JavaPrograms\\Contact Management System\\InputFiles\\AddressFile"));
while((str = br.readLine()) != null)
{
count++;
}
br.close();
} catch (Exception e)
{
}
Object id;
Object name;
data = new Object[count][7];
int i = 0 , j = 0 , m;
try
{
BufferedReader buffrea = new BufferedReader(new FileReader("D:\\JavaPrograms\\Contact Management System\\InputFiles\\AddressFile"));
while((str = buffrea.readLine()) != null)
{
StringTokenizer token = new StringTokenizer(str , "*");
int n = token.countTokens();
id = token.nextElement();
name = token.nextElement();
String strNameLow = name.toString().toLowerCase();
String strNameUpp = name.toString().toUpperCase();
if(strNameLow.startsWith(st.toLowerCase()) || strNameUpp.startsWith(st.toUpperCase()))
{
data[i][0] = id;
data[i][1] = name;
for(j = 2 ; j < n ; j++)
{
data[i][j] = token.nextElement();
}
i = i + 1;
}
}
buffrea.close();
} catch(IOException ioe){
System.out.println("Error : " + ioe.toString());
}
dataArray = new Object[i][7];
for(int a = 0 ; a < i ; a++)
{
for(int b = 0 ; b < 7 ; b++)
{
dataArray[a][b] = data[a][b];
}
}
//Here is the code to print dataArray object which i used but it is not working, when i am run my program it is print "[Ljava.lang.Object;#1cc2e30" in table's first cell[0][0] position
DefaultTableModel model = (DefaultTableModel)this.data_table.getModel();
model.addRow(dataArray);
}
I filled data in a JTable like this. You might want to give it a try adapting it to your code. Variable and stuff are in spanish, just replace them with what you need. In my case it's a table with 4 columns representing a date, a score, duration and max viewers.
private void fillJTable(){
//creating data to add into the JTable. Here you might want to import your proper data from elsewhere
Date date = new Date();
UserReplay rep1 = new UserReplay(date, 12, 13,14);
UserReplay rep2 = new UserReplay(date, 2,34,5);
ArrayList<UserReplay> usuaris = new ArrayList<>();
usuaris.add(rep1);
usuaris.add(rep2);
//----Filling Jtable------
DefaultTableModel model = (DefaultTableModel) view.getTable().getModel();
model.addColumn("Fecha");
model.addColumn("Puntuación");
model.addColumn("Tiempo de duración");
model.addColumn("Pico máximo de espectadores");
for (int i = 0; i < usuaris.size(); i++){
Vector<Date> fecha = new Vector<>(Arrays.asList(usuaris.get(i).getDate()));
Vector<Integer> puntuacion = new Vector<>(Arrays.asList(usuaris.get(i).getPuntuacion()));
Vector<Integer> tiempo = new Vector<>(Arrays.asList(usuaris.get(i).getTiempo()));
Vector<Integer> espectadors = new Vector<>(Arrays.asList(usuaris.get(i).getTiempo()));
Vector<Object> row = new Vector<Object>();
row.addElement(fecha.get(0));
row.addElement(puntuacion.get(0));
row.addElement(tiempo.get(0));
row.addElement(espectadors.get(0));
model.addRow(row);
}
}

android recyclerview json load more items

I'm having this problem a little while, I need to load 25+ items from a database in json. When I load all of the including images etc. the app takes ages to load all of them. So I thought could I load the first five and when I scroll to the bottom the second five and so on. But it does not work. Here is my code:
Scroll listener:
rec.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
visible = lin.getChildCount();
total = lin.getItemCount();
past = lin.findFirstVisibleItemPosition();
if ((visible + past) >= total){
new HttpAsyncTask().loadMore();
}
}
});
AsyncTask:
private class HttpAsyncTask extends AsyncTask<String, Void, List<PostsData>> {
int next;
#Override
protected List<PostsData> doInBackground(String... params) {
try {
//get json from url
JSONObject object = new JSONObject("{'posts':"+GET("http://www.website.com/json")+"}");
//get json array
JSONArray array = object.getJSONArray("posts");
for (int i = 0; i < 5; i++) {
next = i;
PostsData data = new PostsData();
//get object from array
JSONObject jsonObject = array.getJSONObject(i);
//title
data.setTitle(jsonObject.getString("name"));
//id
data.setId(jsonObject.getInt("id"));
JSONObject cat = jsonObject.getJSONObject("category");
//category name
data.setCatagorie(cat.getString("name"));
JSONObject img = jsonObject.getJSONObject("thumbnails");
//image url
String imgUrl = img.getString("preview_url");
//convert url into bitmap
data.setImage(getBitmap(imgUrl));
//get the post submitter name from array 'makers'
String makerFullname = "";
JSONArray userArray = jsonObject.getJSONArray("makers");
for (int j = 0; j < userArray.length(); j++) {
JSONObject user = userArray.getJSONObject(j);
//submitter full name
makerFullname = user.getString("full_name");
data.setUser(makerFullname);
}
data.setSubmitUser(jsonObject.getJSONObject("submitter").getString("full_name"));
//get the like count of the post
data.setLikeCount(jsonObject.getString("upvotes_count"));
list.add(data);
}
}catch (JSONException e){
e.printStackTrace();
}
return list;
}
// onPostExecute displays th
// results of the AsyncTask.
#Override
protected void onPostExecute(List<PostsData> result) {
adapter = new PostsAdapter(result, getContext());
rec.setAdapter(adapter);
}
public void loadMore(){
try {
//get json from url
JSONObject object = new JSONObject("{'posts':" + GET("http://www.materialup.com/api/v1/posts") + "}");
//get json array
JSONArray array = object.getJSONArray("posts");
if (array.length() <= next) {
for (int i = 0; i < next + 5; i++) {
next = i;
PostsData data = new PostsData();
//get object from array
JSONObject jsonObject = array.getJSONObject(i);
//title
data.setTitle(jsonObject.getString("name"));
//id
data.setId(jsonObject.getInt("id"));
JSONObject cat = jsonObject.getJSONObject("category");
//category name
data.setCatagorie(cat.getString("name"));
JSONObject img = jsonObject.getJSONObject("thumbnails");
//image url
String imgUrl = img.getString("preview_url");
//convert url into bitmap
data.setImage(getBitmap(imgUrl));
//get the post submitter name from array 'makers'
String makerFullname = "";
JSONArray userArray = jsonObject.getJSONArray("makers");
for (int j = 0; j < userArray.length(); j++) {
JSONObject user = userArray.getJSONObject(j);
//submitter full name
makerFullname = user.getString("full_name");
data.setUser(makerFullname);
}
data.setSubmitUser(jsonObject.getJSONObject("submitter").getString("full_name"));
//get the like count of the post
data.setLikeCount(jsonObject.getString("upvotes_count"));
list.add(data);
adapter.notifyDataSetChanged();
}
}
}catch(JSONException e){
e.printStackTrace();
}
}.....
It just won't load the next 5 items in the recyclerview. I searched on google but I did not really understand how load more works.
Thanks in advance, Sven.
This is the tutorial I followed: here
Make the next variable a static variable and start the loadMore method for statement with i=next+1,i <next+6 to avoid loading the same data again

Detect and Remove duplicates in ArrayList?

I have an array with 2 positions, each one contains a list of "ids_alunos", the first position has ids_alunos: "1,2,3" and the second:"4,5" but what is happening when I add the ids in my array is this, the first position gets "1,2,3" values and the second: "1,2,3,4,5". why is this happening?
public ArrayList<CadastraEscolas> getFilhos(String mToken) throws Exception {
String[] resposta = new WebService().get("filhos", mToken);
if (resposta[0].equals("200")) {
JSONObject mJSONObject = new JSONObject(resposta[1]);
JSONArray dados = mJSONObject.getJSONArray("data");
mArrayList = new ArrayList<CadastraEscolas>();
mGPSList = new ArrayList<GPSEscolas>();
for (int i = 0; i < dados.length(); i++) {
JSONObject item = dados.getJSONObject(i).getJSONObject("escolas");
JSONArray escolas = item.getJSONArray("data");
for (int j = 0; j < escolas.length(); j++) {
JSONObject jItens = escolas.getJSONObject(j);
mCadastraEscolas = new CadastraEscolas();
mGPSEscolas = new GPSEscolas();
mCadastraEscolas.setId_escola(jItens.optInt("id_escola"));
mGPSEscolas.setId_escola(jItens.optInt("id_escola"));
JSONObject alunos = jItens.optJSONObject("alunos");
JSONArray data = alunos.getJSONArray("data");
if (data != null) {
ArrayList<Filhos> arrayalunos = new ArrayList<Filhos>();
for (int a = 0; a < data.length(); a++) {
mFilhos = new Filhos();
JSONObject clientes = data.getJSONObject(a);
mFilhos.setId_aluno(clientes.optInt("id_aluno"));
arrayalunos.add(mFilhos);
idsAlunos += ";" + arrayalunos.get(a).getId_aluno().toString();
mGPSEscolas.setIds_alunos(idsAlunos);
}
mCadastraEscolas.setalunos(arrayalunos);
}
mArrayList.add(mCadastraEscolas);
mGPSList.add(mGPSEscolas);
}
}
return mArrayList;
} else {
throw new Exception("[" + resposta[0] + "] ERRO: " + resposta[1]);
}
}
You probably want to initialize idsAlunos at the same time as mGPSEscolas, so where you do:
mGPSEscolas = new GPSEscolas();
you could also do:
idsAlunos = "";
otherwise idsAlunos gets appended to with every new mGPSEscolas.

Array throws NullPointerException in Java

I have the following little problem... I have this code that uses the method OpenFile() of one class ReadData to read a .txt file and also I have another class ArraysTZones used to create an object that stores 3 arrays (data1,data2,data3) and 3 integers (total1,total2,total3) returned by the method OpenFile(). The problem is that when I try to display each array (data1,data2,data3) using the method getArray() of ArrayTZones it stops and displays the error NullPointerException. Anyone knows how could I fix this?
public static void main (String args[]) throws IOException {
String fileName = ".//data.txt";
int[] def = new int[180];
try {
ReadData file = new ReadData(fileName);
ArraysTZones summaryatz = new ArraysTZones();
summaryatz = file.OpenFile();
for (int i = 0; i < 180; i++)
System.out.print (summaryatz.getArray1()[i] + " ");
System.out.println ("");
System.out.println (summaryatz.getTotal1());
for (int i = 0; i < 180; i++)
System.out.print (summaryatz.getArray2()[i] + " ");
System.out.println ("");
System.out.println (summaryatz.getTotal2());
for (int i = 0; i < 180; i++)
System.out.print (summaryatz.getArray3()[i] + " ");
System.out.println ("");
System.out.println (summaryatz.getTotal3());
}
catch (IOException e) {
System.out.println(e.getMessage());
}
}
Heres OpenFile()
public ArraysTZones OpenFile() throws IOException {
FileReader reader = new FileReader(path);
BufferedReader textReader = new BufferedReader(reader);
int numberOfTimeZones = 3;
int[] data1 = new int[180];
int[] data2 = new int[180];
int[] data3 = new int[180];
int total1 = 0;
int total2 = 0;
int total3 = 0;
ArraysTZones atz = new ArraysTZones();
for (int i = 0; i < numberOfTimeZones; i++){
if (i == 0) {
String firstTimeZone = textReader.readLine();
String[] val = firstTimeZone.split ("\\s+");
for (int u = 0; u < val.length; u++)
{
int stats = (int)(Math.ceil(Math.abs(Double.parseDouble(val[u]))));
total1 += stats;
data1[u] = stats;
}
total1= total1/180;
atz.setTotal1(total1);
atz.setArray1(data1);
}
else
if (i == 1) {
String secondTimeZone = textReader.readLine();
String[] val = secondTimeZone.split ("\\s+");
for (int u = 0; u < val.length; u++)
{
int stats = (int)(Math.ceil(Math.abs(Double.parseDouble(val[u]))));
total2 += stats;
data2[u] = stats;
}
total2= total2/180;
atz.setTotal2(total2);
atz.setArray2(data2);
}
else {
String thirdTimeZone = textReader.readLine();
String[] val = thirdTimeZone.split ("\\s+");
for (int u = 0; u < val.length; u++)
{
int stats = (int)(Math.ceil(Math.abs(Double.parseDouble(val[u]))));
total3 += stats;
data3[u] = stats;
}
total3= total3/180;
atz.setTotal3(total3);
atz.setArray3(data3);
}
}
textReader.close();
return atz;
}
The getArray()
public int[] getArray1 () {
return data1;
}
And setArray()
public void setArray1 (int[] farray) {
int[] data1 = new int[180];
//int[] farray = new int[180];
data1 = farray;
}
The problem seems to be here
public void setArray1 (int[] farray)
{
int[] data1 = new int[180];
//int[] farray = new int[180];
data1 = farray;
}
You're declaring a new variable called data1 and storing the content of farray to it.
After that method is done, that variable will be removed, due to his scope.
Remove int[] from the line int[] data1 = new int[180]; (or just remove the whole line .. it is unnecessary) and your data will be stored in the correct variable that was declared for the class.
public void setArray1 (int[] farray) {
data1 = farray;
}
You have to initialize ArraysTZones

Categories