如何提高课程?内部类的问题[Android]

时间:2016-05-04 07:24:57

标签: java android optimization inner-classes

我正在使用 Android Studio 来开发我的应用。我有两个活动做同样的事情(参数值除外),我有一个内部类,在其他活动中也做同样的事情。我的内部类扩展了AsyncTask以进行后台下载。但是,如果我从我的第一个活动扩展我的第二个活动,我不能执行task.execute(),我也需要扩展AyncTask,并从Java中不可能扩展两个类。这里是我的代码:

public class MainActivity extends AppCompatActivity {

private RecyclerView recyclerView;
private TextView title;
private List<User> myList;
String query_url;
MyAdapter myAdapter;

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

    recycler = (RecyclerView) findViewById(R.id.recyclerView);
    LinearLayoutManager llm = new LinearLayoutManager(this);
    llm.setOrientation(LinearLayoutManager.VERTICAL);
    recycler.setLayoutManager(llm);

    //create and execute new task
    AsyncDL task = new AsyncDL();
    task.execute();

}

//background download
private class AsyncDL extends AsyncTask<Object, String, Integer> {

    @Override
    protected Integer doInBackground(Object... params) {
        tryDownloadXmlData();
        return null;
    }

    private void tryDownloadXmlData() {
        try {
            URL xmlUrl = new URL(query_url);
            myXMLPullParser myCustomParser = new myXMLPullParser();

            //fetch & parse data
            myList = myCustomParser.parse(xmlUrl.openStream());

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onPostExecute(Integer integer) {
        myAdapter = new MyAdapter(getApplicationContext(), myList);
        recycler.setAdapter(myAdapter);

         RecyclerItemClickSupport.addTo(recycler).setOnItemClickListener(new RecyclerItemClickSupport.OnItemClickListener() {
            @Override
            public void onItemClicked(RecyclerView recyclerView, int position, View v) {
                User user = myList.get(position);
                Intent myIntent = new Intent(getApplicationContext(), Details.class);
                myIntent.putExtra("user", user);
                startActivity(myIntent);
            }
        });
        super.onPostExecute(integer);
    }
}

}

我真的不知道是否有可能重复使用这样的活动代码,谢谢!

编辑:新代码

ProductAsyncTask task = new ProductAsyncTask(getApplicationContext(), listview, QUERY_URL, productList, myCustomAdapter);
task.execute();

listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

            User currentUser = myList.get(position); //error here
            Intent myIntent = new Intent(getApplicationContext(), Detail_User.class);

            myIntent.putExtra("currentUser", currentUser);
            Log.i("INFO", "Loading extra data for transfer...");

            startActivity(myIntent);
        }
    });

0 个答案:

没有答案