0

hope you fine and well,

i have the following main class :

public class MainActivity extends AppCompatActivity {
    Activity activity;

    ViewPager viewPager;
    CustomAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        viewPager=(ViewPager)findViewById(R.id.view_pager);
        adapter=new CustomAdapter(this);
        viewPager.setAdapter(adapter);

                ConnectionAsyncTask connectionAsyncTask = new
                ConnectionAsyncTask(MainActivity.this);
                connectionAsyncTask.execute("http://www.mocky.io/v2/570d3677270000f600dc29b6");
    }

    public void showUploader()
    {
       // findViewById(R.id.progressBar1).setVisibility(View.VISIBLE);
    }
    public void hideUploader()
    {
        //findViewById(R.id.progressBar1).setVisibility(View.GONE);
    }


    public void DisplyOnTextView(List< Student > students) {

        List  <Student> my = students ;

    }             
}

when i run the app, this main activity will use another class to read json data from link as follows:

public class StudentJasonParser {
    public static List<Student> getObjectFromJason(String jason)
    {
        List<Student> students;
        try {
            JSONArray jsonArray = new JSONArray(jason);
            students = new ArrayList<>();
            for(int i=0;i<jsonArray.length();i++)
            {
                JSONObject jsonObject = new JSONObject();
                jsonObject= (JSONObject) jsonArray.get(i);
                Student student = new Student();
                student.setID(jsonObject.getInt("id"));
                student.setName(jsonObject.getString("name"));
                student.setUrl(jsonObject.getString("url"));
                student.setDes(jsonObject.getString("des\n"));
                student.setRate(jsonObject.getDouble("rate"));
                student.setLon(jsonObject.getDouble("lon"));
                student.setLat(jsonObject.getDouble("lat"));
                students.add(student);
            }
        } catch (JSONException e) {
            e.printStackTrace();
            return null;
        }
        return students;
    }
}

now this class will return the data to the following class :

public class ConnectionAsyncTask extends AsyncTask<String,String,String> {
    Activity activity;
    public ConnectionAsyncTask(Activity activity) {
        this.activity=activity;
    }
    @Override
    protected void onPreExecute() {
        //((MainActivity)activity).DisplyOnTextView();
        ((MainActivity)activity).showUploader();
    }
    @Override
    protected String doInBackground(String... params) {
        String content =HttpManager.getData(params[0]);
        return content;
    }
    @Override
    protected void onProgressUpdate(String... values) {
        super.onProgressUpdate(values);
    }
    @Override
    protected void onPostExecute(String s) {
        ((MainActivity)activity).hideUploader();
        List<Student> students= StudentJasonParser.getObjectFromJason(s);
        if (students != null) {

                    ((MainActivity) activity).DisplyOnTextView(students);
        }
   }
}

this line : ((MainActivity)activity).DisplyOnTextView(students);

will return the fetched data to the main class in the following function (mentioned in the main class ! )

public void DisplyOnTextView(List< Student > students) {

        List  <Student> my = students ;

    }

now what i want is to pass this list to the following class in order to use it in the imageView and textView in the viewPager instead of the pre-defined data in the class :

public class CustomAdapter extends PagerAdapter {

    private int[] images = {R.drawable.sample_0,R.drawable.sample_1};
    private Context ctx;
    private LayoutInflater LayoutInflater;

    public CustomAdapter(Context ctx)
    {
        this.ctx=ctx;
    }

    @Override
    public int getCount() {
        return images.length;
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return (view==(LinearLayout)object);
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {



        LayoutInflater = (LayoutInflater)ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View view = LayoutInflater.inflate(R.layout.slide_layout,container,false);
        ImageView imageView =(ImageView) view.findViewById(R.id.image_view);
        TextView textView = (TextView)view.findViewById(R.id.image_count);
        imageView.setImageResource(images[position]);

        textView.setText(""+position);
        container.addView(view);
        return view;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        container.removeView((LinearLayout) object);
    }



}

any idea ?!

thanks, regards.

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
MSMC
  • 141
  • 1
  • 5
  • 16
  • without seeing the rest of the code, `new CustomAdapter(getContext(), list)` is a good start – OneCricketeer Apr 24 '16 at 20:33
  • Possible duplicate of [Custom Adapter for List View](http://stackoverflow.com/questions/8166497/custom-adapter-for-list-view) – OneCricketeer Apr 24 '16 at 20:35
  • in the given link, he extends ArrayAdapter in the CustomAdapter class, but h already extends pagerAdapter, and as you know we cant extends two clases ! could you please help me ! – MSMC Apr 24 '16 at 20:48
  • I don't know what you want to do... Please [edit] your question with a [mcve] with inputs and expected output. Maybe follow a proper tutorial on custom ArrayAdapters – OneCricketeer Apr 24 '16 at 20:53
  • It would appear you are using a PagerAdapter, though, but ArrayAdapter follows the same concept – OneCricketeer Apr 24 '16 at 20:55
  • i edited and updated all of the question with all of my code ! please help me . – MSMC Apr 24 '16 at 21:10
  • Is your question about the adapter or what to do in the `DisplyOnTextView` method? Because 1) no offense, you're going about using the AsyncTask incorrectly 2) there is no TextView to display anything on in the activity itself – OneCricketeer Apr 24 '16 at 21:13
  • Who calls `JSON` "Jason"? :D I know Im not being of much help, it just cracked me up. – Vucko Apr 24 '16 at 21:25
  • Here's some recommendations since you seem to be doing some parameter passing already, so I assume you know how it works. 1) How would you move the `int[]` in the adapter to be used as a parameter? 2) Try making that an Arraylist of integers instead of an array 3) What methods could you use to add additional integers to that arraylist by using your custom adapter? – OneCricketeer Apr 24 '16 at 21:48
  • i think that i must cancel all the work on the Android project and to resume works on the graduation project ! thank you guys ! really thanks ! – MSMC Apr 24 '16 at 21:55

1 Answers1

1

what i want is to pass this list to the following class in order to use it in the imageView and textView in the viewPager

Then simply pass in the list as a parameter to the adapter and add a member variable for it. The usage of this adapter is at the bottom of this post, because I want to mention some other stuff.

class CustomAdapter extends PagerAdapter {
    private Context ctx;
    private List<Student> data;

    public CustomAdapter(Context ctx, List<Student> students) {
        this.ctx = ctx;
        this.data = students;
    }

If you want to use that data variable in the instantiateItem method, then you can do Student s = this.data.get(position); and use the various methods on the Student object to load the TextView or ImageView.


Please note that you will need an image loading library (Picasso, Glide, Fresco, etc.) to load a URL into an ImageView. While on the topic of libraries, though, you will save yourself much development time by looking into Gson for JSON parsing and Retrofit or Volley for HTTP network calls with JSON data.


As for your usage of the AsyncTask, passing around the Activity variable is bad practice. Try to use an asynchronous callback to the Activity instead.

public interface AsyncResponse<T> {
    void onResponse(T response);
} 
public class ConnectionAsyncTask extends AsyncTask<String, Void, List<Student>> {

    private AsyncResponse<List<Student>> callback;

    public ConnectionAsyncTask(AsyncResponse<List<Student>> callback) {
        this.callback = callback;
    }

    @Override
    protected List<User> doInBackground(String... params) {
        String url = params[0];
        final List<Student> students = new ArrayList<Student>();

        // TODO: JSON stuff
        return students;
    }

    @Override
    protected void onPostExecute(List<Student> result) {
        if (this.callback != null) {
            this.callback.onResponse(result);
        } else {
            Log.w("ConnectionAsyncTask", "Ignoring result");
        }
    }
}
public class SampleViewPagerActivity extends Activity {

    private ViewPager pager;
    private PagerAdapter adapter;
    private ArrayList<Student> students;
    private ProgressDialog progress;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 1. Inflate a layout
        setContentView(R.layout.viewpager_activity);

        // 2. Initialize the views
        this.pager = (ViewPager) findViewById(R.id.pager);
        this.progress = new ProgressDialog(this);
        this.progress.setTitle("Loading");
        this.progress.setMessage("Please wait");

        // 3. Populate the views with data
        this.students = new ArrayList<Student>();
        this.adapter = new CustomAdapter(this, students);
        this.pager.setAdapter(adapter);

        // This code runs later, after 'execute' is called and the response is returned
        ConnectionAsyncTask task = new ConnectionAsyncTask(new AsyncResponse<List<Student>>() {
            @Override
            public void onResponse(List<Student> response) {
                students.clear();
                students.addAll(response);
                adapter.notifyDataSetChanged();

                progress.hide();
            }
        });

        // Optionally show some progress while waiting
        this.progress.show();

        // TODO: Use real URL
        task.execute("http://www.somesite.com/data");
    }
}
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245