im using android studio for a school project and im in the final stages now. the only thing i have left is for one class that has 2 spinners, one determining the program, and the other determining the semester, and a button that will then take those two spinners and spit out a URL pertaining to the schedule of that program and semester. The problem is, i dont know how to then take that spit out URL, and parse it into the other java class that displays a schedule. Below you will find the code attached, that works but doesnt display the correct schedule(since its hardcoded)
StringBuffer sb = new StringBuffer();
sb.append("http://branko-cirovic.appspot.com/etcapp/timetables/timetable_"); sb.append(cid); sb.append(semester); sb.append(".xml");
loc = sb.toString();
Toast.makeText(ScheduleMainActivity.this,"You Selected : "
+ loc, Toast.LENGTH_SHORT).show();
Intent toy7 = new Intent(ScheduleMainActivity.this, TimetableMainActivity.class);
toy7.putExtra("Name", loc);
startActivity(toy7);
That is the activity where im creating the intent and using the putExtra to use the data in the next activity
public class GetXML extends AsyncTask<String, Void, String> {
String src = null;
String loc = (String) getIntent().getExtras().get("Name");
#Override
protected String doInBackground(String... params) {
try {
URL url = new URL(loc);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
src = readStream(con.getInputStream());
} catch (Exception e) {
e.printStackTrace();
}
return src;
}
#Override
protected void onPostExecute(String result) {
if (src == null)
new AlertDialog.Builder(TimetableMainActivity.this).
setTitle("Error").setMessage("No Schedule Found").
setNeutralButton("Close", null).show();
else {
parseXML(src);
}
setContentView(R.layout.activity_main_timetable);
days = new String[5][10];
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 10; j++) {
int k = i * 10 + j;
days[i][j] = schedule.get(k);
}
}
for (int i = 0; i < 5; i++)
list[i] = new ArrayList<Map<String, String>>();
int count = hours.length;
for (int j = 0; j < 5; j++) {
for (int i = 0; i < count; i++) {
map = new HashMap<String, String>();
map.put("time", hours[i]);
map.put("description", days[j][i]);
list[j].add(map);
}
}
Calendar cal = Calendar.getInstance();
int today = cal.get(Calendar.DAY_OF_WEEK) - 2;
pos = 0;
if (today >= 0 && today <= 4)
pos = today;
ViewPager viewPager = findViewById(R.id.ViewPager);
CustomPagerAdapter adapter = new CustomPagerAdapter(TimetableMainActivity.this, list);
PagerTabStrip pagerTabStrip = findViewById(R.id.pager_tab);
int color = Color.parseColor("#33b7ee");
pagerTabStrip.setTabIndicatorColor(color);
viewPager.setAdapter(adapter);
viewPager.setCurrentItem(pos);
}
This is where im getting an error. Im getting an IndexOut of bounds error and the app is crashing
2018-11-20 22:35:19.126 20681-20681/com.example.mr_ru.listview E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.mr_ru.listview, PID: 20681
java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.get(ArrayList.java:437)
at com.example.mr_ru.listview.TimetableMainActivity$GetXML.onPostExecute(TimetableMainActivity.java:100)
at com.example.mr_ru.listview.TimetableMainActivity$GetXML.onPostExecute(TimetableMainActivity.java:66)
at android.os.AsyncTask.finish(AsyncTask.java:695)
at android.os.AsyncTask.access$600(AsyncTask.java:180)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:712)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
This is the error btw
Related
This question already has answers here:
The application may be doing too much work on its main thread
(21 answers)
Closed 1 year ago.
I have a block of code to load a table view. But for large data, my app is crashing. I want to fix that and also want to show a progress bar while loading the table view data. I tried with the AsyncTask but it is showing Skipped 98 frames! The application may be doing too much work on its main thread.
My onCreate code (Updated): -
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sheet);
myDb = new DBHelper(this);
loadIntentInputs();
setToolbar();
new MyWorker(this).execute();
}
My AsyncTask code (Updated): -
public class MyWorker extends AsyncTask < String , Context , Void > {
private Context context ;
private ProgressDialog progressDialog;
public MyWorker (Context context) {
this.context = context ;
progressDialog = new ProgressDialog ( context ) ;
progressDialog.setCancelable ( false ) ;
progressDialog.setMessage ( "Retrieving data..." ) ;
progressDialog.setTitle ( "Please wait" ) ;
progressDialog.setIndeterminate ( true ) ;
}
# Override
protected void onPreExecute ( ) {
progressDialog.show () ;
}
# Override
protected Void doInBackground ( String ... params ) {
runOnUiThread(new Runnable() {
#Override
public void run() {
showAttendanceTable();
}
});
return null ;
}
# Override
protected void onPostExecute ( Void result ) {
if(progressDialog != null && progressDialog.isShowing()){
progressDialog.dismiss ( ) ;
}
}
}
showAttendanceTable method code (Updated): -
private void showAttendanceTable() {
TableLayout tableLayout = findViewById(R.id.table_layout);
int day_in_month = getDayInMonth(month_year);
int row_size = sid_array.length+1;
TableRow[] rows = new TableRow[row_size];
TextView[] rolls_tv = new TextView[row_size];
TextView[] names_tv = new TextView[row_size];
TextView[][] status_tv = new TextView[row_size][day_in_month+1];
for (int i = 0; i < row_size; i++) {
rolls_tv[i] = new TextView(this);
names_tv[i] = new TextView(this);
for (int j = 1; j <= day_in_month; j++) {
status_tv[i][j] = new TextView(this);
}
}
// for excel file
HSSFSheet hssfSheet = null;
try {
hssfSheet = hssfWorkbook.createSheet(month_year);
} catch (IllegalArgumentException e){
e.printStackTrace();
}
HSSFRow hssfRow;
// setting 1st row
rolls_tv[0].setText("Roll");
names_tv[0].setText("Name");
// setting excel file
hssfRow = hssfSheet.createRow(0);
hssfRow.createCell(0).setCellValue("Roll");
hssfRow.createCell(1).setCellValue("Name");
rolls_tv[0].setTextSize(1,22);
names_tv[0].setTextSize(1,22);
rolls_tv[0].setTypeface(rolls_tv[0].getTypeface(), Typeface.BOLD);
names_tv[0].setTypeface(names_tv[0].getTypeface(), Typeface.BOLD);
rolls_tv[0].setTextAlignment(View.TEXT_ALIGNMENT_CENTER);
names_tv[0].setTextAlignment(View.TEXT_ALIGNMENT_CENTER);
rolls_tv[0].setTextColor(Color.parseColor("#FF000000"));
names_tv[0].setTextColor(Color.parseColor("#FF000000"));
for (int i = 1; i <=day_in_month ; i++) {
String date = String.valueOf(i);
if(i<10) date = "0"+date;
status_tv[0][i].setText(date);
// setting excel file
hssfRow.createCell(i+1).setCellValue(date);
status_tv[0][i].setTextSize(1,22);
status_tv[0][i].setTypeface(status_tv[0][i].getTypeface(), Typeface.BOLD);
status_tv[0][i].setTextAlignment(View.TEXT_ALIGNMENT_CENTER);
status_tv[0][i].setTextColor(Color.parseColor("#FF000000"));
}
// setting rows after 1st row
for (int i = 1; i < row_size ; i++) {
rolls_tv[i].setText(roll_array[i-1]);
names_tv[i].setText(name_array[i-1]);
// setting excel file
hssfRow = hssfSheet.createRow(i);
hssfRow.createCell(0).setCellValue(roll_array[i-1]);
hssfRow.createCell(1).setCellValue(name_array[i-1]);
rolls_tv[i].setTextSize(1,20);
names_tv[i].setTextSize(1,20);
rolls_tv[i].setTextAlignment(View.TEXT_ALIGNMENT_CENTER);
names_tv[i].setTextAlignment(View.TEXT_ALIGNMENT_CENTER);
rolls_tv[i].setTextColor(Color.parseColor("#FF000000"));
names_tv[i].setTextColor(Color.parseColor("#FF000000"));
int count=0;
for (int j = 1; j <=day_in_month ; j++) {
String day = String.valueOf(j);
String month = month_year.substring(0,3);
String year = month_year.substring(4,8);
String status = myDb.getStatus(sid_array[i-1],day+" "+month+" "+year);
if (status!=null && status.equals("A")) {
status_tv[i][j].setText(status);
status_tv[i][j].setBackgroundColor(Color.parseColor("#EF9A9A"));
// setting excel file
hssfRow.createCell(j+1).setCellValue(status);
} else if (status!=null && status.equals("P")) {
status_tv[i][j].setText(String.valueOf(++count));
status_tv[i][j].setBackgroundColor(Color.parseColor("#A5D6A7"));
// setting excel file
hssfRow.createCell(j+1).setCellValue(String.valueOf(count));
}
status_tv[i][j].setTextSize(1,20);
status_tv[i][j].setTextAlignment(View.TEXT_ALIGNMENT_CENTER);
status_tv[i][j].setTextColor(Color.parseColor("#FF000000"));
}
}
for (int i = 0; i < row_size; i++) {
rows[i] = new TableRow(this);
rolls_tv[i].setPadding(20,12,20,12);
names_tv[i].setPadding(20,12,20,12);
if (i==0) {
rows[i].setBackgroundColor(Color.parseColor("#FFD400"));
} else if(i%2==0) {
rows[i].setBackgroundColor(Color.parseColor("#EEEEEE"));
} else {
rows[i].setBackgroundColor(Color.parseColor("#E4E4E4"));
}
rows[i].addView(rolls_tv[i]);
rows[i].addView(names_tv[i]);
for (int j = 1; j <=day_in_month ; j++) {
status_tv[i][j].setPadding(20,12,20,12);
rows[i].addView(status_tv[i][j]);
}
tableLayout.addView(rows[i]);
}
tableLayout.setShowDividers(TableLayout.SHOW_DIVIDER_MIDDLE);
}
The problem is you are running new thread on your doInBackground method and you have placed your showAttendanceTable() code inside runOnUiThread() which is causing too many work to consume main thread.Just copy paste the below code, replace it with your doInBackground() method and everything will work fine.
protected Void doInBackground ( String ... params ) {
showAttendanceTable();
}
return null ;
}
Copy this much part of your code from showAttendanceTable() to onPreExecute() method:
TableLayout tableLayout = findViewById(R.id.table_layout);
int day_in_month = getDayInMonth(month_year);
int row_size = sid_array.length+1;
TableRow[] rows = new TableRow[row_size];
TextView[] rolls_tv = new TextView[row_size];
TextView[] names_tv = new TextView[row_size];
TextView[][] status_tv = new TextView[row_size][day_in_month+1];
for (int i = 0; i < row_size; i++) {
rolls_tv[i] = new TextView(this);
names_tv[i] = new TextView(this);
for (int j = 1; j <= day_in_month; j++) {
status_tv[i][j] = new TextView(this);
}
}
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 3 years ago.
I have a list of number of url and its name is listOfUrlSources,
I passed it inside class GenerateUrlImages the task of this class is to come out with a picture link and it works if you use it and pass a link to one site it gives out a picture link, but now I'm trying to pass more than one site for it and also give me links to photos I tried, but I didn't make it through a list.
//
for (int i = 0; i < sources.size(); i++) {
item = new GenerateImage(sources.get(i).getUrl());
// networkImagesLiveData.setValue(createLiveDataForLoadingImage(sources.get(i).getUrl()));
listOfUrlSources.add(item);
}
new GenerateUrlImages().execute(listOfUrlSources);
//---------
//
public class GenerateUrlImages extends AsyncTask<List<GenerateImage>, Void, List<GenerateImage>>{
public GenerateUrlImages(){
}
#Override
protected List<GenerateImage> doInBackground(List<GenerateImage>... arrayLists) {
List<String> result = new ArrayList<String>();
List<GenerateImage> passed = new ArrayList<GenerateImage>();
passed = arrayLists[0];
//get passed arraylist
//urlImages
String src="";
try {
org.jsoup.nodes.Document doc1;
Elements img2;
GenerateImage Item;
for(int i=0; i<passed.size(); i++) {
doc1 = Jsoup.connect(passed.get(i).getUrl()).get();
//Elements img = doc1.getElementsByTag("img");
img2 = doc1.getElementsByTag("meta");
for(Element element : img2) {
if("og:image".equals(element.attr("property"))) {
src = element.attr("content");
Item = new GenerateImage(src);
urlImages.add(Item);
}
}
for (int j = 0; j < urlImages.size(); j++) {
Log.d("getUrlImage:", "" + urlImages(j));
}
}
//InputStream in = new java.net.URL(src).openStream();
// bmp = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error :", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPreExecute(){
}
protected void onPostExecute(ArrayList<String> result){
}
}
In for loop you did a mistake
for (int j = 0; j < urlImages.size(); j++) {
Log.d("getUrlImage: ", "" + urlImages[j]); // add this line also
}
You have printed the Arraylist without index value using the ArraylistName.get(index) in your case Log.d("getUrlImage: ", "" + urlImages); it should be like Log.d("getUrlImage: ", "" + urlImages.get(j));
after this change in your code, you will be able to see the required result.
for (int j = 0; j < urlImages.size(); j++) {
Log.d("getUrlImage: ", "" + urlImages.get(j));
}
I am creating a function for an app where the user supplies some items and the app then the app gets prices from a database. These prices are put in a map , and after async task is complete , the permutation function starts. What it IS meant to do id to go through all permutations based on combinations which change based on input from the user.I am getting ava.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.Integer.intValue()' on a null object referenceMy code is as follows:
latest.java
public class latest extends AppCompatActivity {
String major = "";
TextView textView;
public static Map<String,Map<String,Integer>> cart_names = new HashMap<>();
public static Map<String,Map<String,Integer>> cart_names2 = new HashMap<>();
ProgressDialog pd;
ArrayList<String> strhold = new ArrayList<String>();
Activity context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_latest);
Toolbar toolbar = (Toolbar) findViewById(R.id.app_bar);
setSupportActionBar(toolbar);
textView = (TextView) findViewById(R.id.main_text);
context=this;
for (int s=0;s<Search_multiple.cart_records.size();s++){
strhold.add(Search_multiple.cart_records.get(s).getName());
}
if (strhold.size()>0) {
BackTask backTask = new BackTask();
backTask.execute(strhold);
}
}
#Override
public void onStart(){
super.onStart();
String arr[]={};
}
public void goto_main_confirm(View view) {
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
}
/* public static void setCart_records(Items item){
cart_records.add(item);
}*/
public void goto_cart_confirm(View view) {
Intent someintent = new Intent(this, CartActiviy.class);
startActivity(someintent);
}
private class BackTask extends AsyncTask<ArrayList<String>, Void, Void> {
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(context);
pd.setTitle("Retrieving data");
pd.setMessage("Please wait.");
pd.setCancelable(true);
pd.setIndeterminate(true);
pd.show();
}
protected Void doInBackground(ArrayList<String>... arg0) {
InputStream is = null;
String result = "";
try {
ArrayList<String> name = arg0[0];
String link = "http://chutte.co.nf/get_item_prices.php?";
for (int b = 0; b < name.size(); b++) {
link += "names[]" + "=" + name.get(b);
if (b != name.size() - 1) {
link += "&";
}
}
Log.e("ERROR", link);
URL url = new URL(link);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
is = urlConnection.getInputStream();
} catch (Exception e) {
if (pd != null)
pd.dismiss();
Log.e("ERROR", e.getMessage());
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder builder = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
builder.append(line + "\n");
}
is.close();
result = builder.toString();
} catch (Exception e) {
Log.e("ERROR", "Error converting result " + e.toString());
}
try {
result = result.substring(result.indexOf("["));
JSONArray jsonArray = new JSONArray(result);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
Map<String, Integer> temmap = new HashMap<>();
String temname = jsonObject.getString("Name");
temmap.put("First", jsonObject.getInt("First"));
strhold.add("First");
temmap.put("Second", jsonObject.getInt("Second"));
strhold.add("Second");
temmap.put("Third", jsonObject.getInt("Third"));
strhold.add("Third");
Log.e("ERROR", temmap.get("First").toString());
cart_names.put(temname, temmap);
}
} catch (Exception e) {
Log.e("ERROR", "Error pasting data " + e.toString());
}
return null;
}
protected void onPostExecute(Void result) {
if (pd != null) pd.dismiss();
Log.e("size", cart_names.size() + " ");
if (cart_names.size() == 0) {
textView.setText("Sorry, Error applying data \n" + "Please contact customer service........");
} else {
String[] strhold1 = new String[strhold.size()];
for (int i = 0; i < strhold.size(); i++) {
strhold1[i] = strhold.get(i);
}
Combination.printCombination(strhold1, strhold.size(), 2);
}
}
}
}
Combination.java
Public class Combination {
/* arr[] ---> Input Array
data[] ---> Temporary array to store current combination
start & end ---> Staring and Ending indexes in arr[]
index ---> Current index in data[]
r ---> Size of a combination to be printed */
public static ArrayList<String> finalmap = new ArrayList<>();
public static void combinationUtil(String arr[], String data[], int start,
int end, int index, int r)
{
// Current combination is ready to be printed, print it
if (index == r)
{
ArrayList<String> stringArrayList = new ArrayList<String>();
for (int j=0; j<r; j++)
stringArrayList.add(data[j]);
permute(stringArrayList,0);
return;
}
// replace index with all possible elements. The condition
// "end-i+1 >= r-index" makes sure that including one element
// at index will make a combination with remaining elements
// at remaining positions
for (int i=start; i<=end && end-i+1 >= r-index; i++)
{
data[index] = arr[i];
combinationUtil(arr, data, i+1, end, index+1, r);
}
}
// The main function that prints all combinations of size r
// in arr[] of size n. This function mainly uses combinationUtil()
public static void printCombination(String arr[], int n, int r)
{
// A temporary array to store all combination one by one
String data[]=new String[r];
for(int no = 0;no<arr.length;no++){
boolean decider = true;
for (Map.Entry<String,Map<String,Integer>> entry : latest.cart_names.entrySet()){
if(latest.cart_names.get(entry.getKey()).get(arr[no])==0){
decider=false;
}
}
if (finalmap.size()==0) {
if (decider) {
for (int rt = 0; rt < latest.cart_names.size(); rt++) {
finalmap.add(arr[no]);
}
}
}else{
if (decider) {
int sum1 = 0;
int sum2 = 0;
for (Map.Entry<String, Map<String, Integer>> entry : latest.cart_names.entrySet()) {
sum1 += latest.cart_names.get(entry.getKey()).get(finalmap);
sum2 += latest.cart_names.get(entry.getKey()).get(arr[no]);
}
if (sum2>sum1){
for (int rt = 0; rt < latest.cart_names.size(); rt++) {
finalmap.add(arr[no]);
}
}
}
}
}
// Print all combination using temprary array 'data[]'
combinationUtil(arr, data, 0, n-1, 0, r);
}
public static void permute(ArrayList<String> arr, int k){
for(int i = k; i < arr.size(); i++){
java.util.Collections.swap(arr, i, k);
/*int sum1 = 0;
int sum2 = 0;
int man = 0;
for (Map.Entry<String, Map<String, Integer>> entry : latest.cart_names.entrySet()) {
sum1 += latest.cart_names.get(entry.getKey()).get(finalmap);
sum2+=latest.cart_names.get(entry.getKey()).get(arr.get(man));
man++;
}
if (sum2>sum1){
for (int rt = 0; rt < latest.cart_names.size(); rt++) {
finalmap.add(arr.get(rt));
}
}*/
permute(arr, k+1);
java.util.Collections.swap(arr, k, i);
/* for (Map.Entry<String, Map<String, Integer>> entry : latest.cart_names.entrySet()) {
sum1 += latest.cart_names.get(entry.getKey()).get(finalmap);
sum2+=latest.cart_names.get(entry.getKey()).get(arr.get(man));
man++;
}
if (sum2>sum1){
for (int rt = 0; rt < latest.cart_names.size(); rt++) {
finalmap.add(arr.get(rt));
}
}
}
if (k == arr.size() -1){
for(int woman = 0;woman<finalmap.size();woman++) {
System.out.println(finalmap.get(woman));
}*/
}
}
}
Log
6-15 15:06:41.850 3538-3538/nf.co.riaah.chutte D/AndroidRuntime: Shutting down VM
--------- beginning of crash
06-15 15:06:41.850 3538-3538/nf.co.riaah.chutte E/AndroidRuntime: FATAL EXCEPTION: main
Process: nf.co.riaah.chutte, PID: 3538
java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.Integer.intValue()' on a null object reference
at nf.co.riaah.chutte.Combination.printCombination(Combination.java:54)
at nf.co.riaah.chutte.latest$BackTask.onPostExecute(latest.java:173)
at nf.co.riaah.chutte.latest$BackTask.onPostExecute(latest.java:83)
at android.os.AsyncTask.finish(AsyncTask.java:636)
at android.os.AsyncTask.access$500(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:653)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:139)
at android.app.ActivityThread.main(ActivityThread.java:5298)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:950)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:745)
06-15 15:06:41.851 3538-3538/nf.co.riaah.chutte D/AppTracker: App Event: crash
06-15 15:06:41.883 3538-3538/nf.co.riaah.chutte I/Process: Sending signal. PID: 3538 SIG: 9
06-15 15:06:43.255 3918-3918/nf.co.riaah.chutte D/ThreadedRenderer: mThreadGroupCpuId 2 mRenderThreadCpuId 2 affinity
Have a look at Combination.java line 54 wich seams to be if(latest.cart_names.get(entry.getKey()).get(arr[no])==0) (If I counted correctly) so the Integer in the Map seams to be null. I recommend so add some log-output or to debug to find out which entry exactly is the problem and than check if you need to add a bull-check or fix your data.
Maybe arr[no] is null.
I recommend to split the line and make some log-outputs to find the problem (or use a debugger)
To find the cause of the problem I would replace:
if(latest.cart_names.get(entry.getKey()).get(arr[no])==0)
to
System.err.println("no: "+no);
String arrayElement=arr[no];
System.err.println("arrayElement: "+arrayElement);
Map<String,Integer> outerMapValue = entry.getValue();
System.err.println("outerMapValue: "+outerMapValue);
if(outerMapValue.get(arrayElement)==0)
Remarks:
if(latest.cart_names.get(entry.getKey()) can be replaced with entry.getValue()
Map<String,Map<String,Integer>> Is not very easy to understand while reading the code. You may consider to introduce a type to wrap the inner Map<String,Integer>
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
How do I set an array to change the URL of an Async download task for multiple butons?
This isn't working and I am not sure how to fix it.
final String[] dlUrl = new String[]{"www.google.com/document.pdf", "www.google.com/document2.pdf", "www.google.com/document3.pdf"};{
for(int k = 0; i < dlUrl.length; i++) {
final String dlUrl = downloadFile.execute([k]);
}
I am trying to have it change the following code section:
private void startDownload() {
DownloadFile downloadFile = new DownloadFile();
downloadFile.execute("http://www.google.com/doc.pdf");
}
And the Async Task itself:
class DownloadFile extends AsyncTask<String, Integer, String> {
URL url = new URL(aurl[0]);
URLConnection connection = url.openConnection();
I have a similar array that picks up button presses, I want to try to add this to it... Any ideas?
final OnClickListener listener = new OnClickListener() {
public void onClick(View v){
switch(v.getId()){
case R.id.sec1:
break;
case R.id.sec2:
break;
case R.id.sec3:
break;
}
}
};
final int[] btnIds = new int[]{R.id.sec1, R.id.sec2, R.id.sec3};{
for(int i = 0; i < btnIds.length; i++) {
final Button btn = (Button) findViewById (btnIds[i]);
btn.setOnClickListener(listener);
}
final String[] dlUrl = new String[]{"www.google.com/document.pdf",
"www.google.com/document2.pdf",
"www.google.com/document3.pdf"};{
for(int k = 0; i < dlUrl.length; i++) {
final String dlUrl = downloadFile.execute([k]);
}
should probably be something more like
final String[] dlUrl = new String[]{"www.google.com/document.pdf",
"www.google.com/document2.pdf",
"www.google.com/document3.pdf"}; // { removed
for(int k = 0; k < dlUrl.length; k++) {
^
final String currentUrl = dlUrl[k];
^^^^^^^^
downloadFile.execute(currentUrl);
}
Regarding your own comment:
Learning Java and android through trial and error is difficult
...and an extremely bad idea I must add.