简体   繁体   中英

Android refresh button best practices?

Hi Having an activity that loads a twitter feed.
Android Twitter String to Json Array .

I'm wanting to put a refresh button at the top that when clicked reloads the data.

so far i've got it to just reload the activity is this the best way of doing this?

    package co.uk.fantasticmedia.TheEvoStikLeague;


import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;



import android.app.ListActivity;



public class TwitterActivity extends ListActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);

    setContentView(R.layout.twitteract);


    Button refresh = (Button) findViewById(R.id.btn_refresh);

    //Listening to button event
    refresh.setOnClickListener(new View.OnClickListener() {

        public void onClick(View arg0) {
            //Starting a new Intent
            Intent reload = new Intent(getApplicationContext(), TwitterActivity.class);



            startActivity(reload);


        }
    });





     try{
            // Create a new HTTP Client
            DefaultHttpClient defaultClient = new DefaultHttpClient();
            // Setup the get request
            HttpGet httpGetRequest = new HttpGet("https://api.twitter.com/1/statuses/user_timeline.json?screen_name=evostikleague&count=10");

            // Execute the request in the client
            HttpResponse httpResponse = defaultClient.execute(httpGetRequest);
            // Grab the response
            BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8"));
            String json = reader.readLine();

            Log.v(json,"jsonfeed");




            List<String> items = new ArrayList<String>();

              //items.add(json);


            JSONArray jArray = new JSONArray(json);


            for (int i=0; i < jArray.length(); i++)
            {    JSONObject oneObject = jArray.getJSONObject(i);
                items.add(oneObject.getString("text"));
                 Log.i("items", "items");
            }

            setListAdapter ( new ArrayAdapter<String>(this, R.layout.single_item, items));
            ListView list = getListView();
            list.setTextFilterEnabled(true);


            list.setOnItemClickListener(new OnItemClickListener(){

                public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                        long arg3) {
                    // TODO Auto-generated method stub
                    Toast.makeText(getApplicationContext(), ((TextView) arg1).getText(),1000).show();
                }



            });


        } catch(Exception e){
            // In your production code handle any errors and catch the individual exceptions
            e.printStackTrace();
        }

    }

















    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        if (item.getItemId() == R.id.home) {

            startActivity(new Intent(TwitterActivity.this, HomeActivity.class));

            return(true);
      }


        if (item.getItemId() == R.id.match) {

            startActivity(new Intent(TwitterActivity.this, MatchActivity.class));

            return(true);
      }



        if (item.getItemId() == R.id.teams) {

            startActivity(new Intent(TwitterActivity.this, TeamsActivity.class));

            return(true);
      }



        if (item.getItemId() == R.id.twitter) {

            startActivity(new Intent(TwitterActivity.this, TwitterActivity.class));

            return(true);
      }

        if (item.getItemId() == R.id.info) {

            startActivity(new Intent(TwitterActivity.this, InfoActivity.class));

            return(true);
      }


        return(super.onOptionsItemSelected(item));


    }




}

Use Menus to provide Refresh option. So when the user presses Menu button on phone, they can choose Refresh command to reload tweets

can you post the rest of your activity? Especially the portion that you are using to load the list the first time.

Probably it is unnecessary to restart the entire activity. You just need to move the portion of your code that populates the list for you into its own method. Then you can call that method when the user wants to refresh.

If nothing else you should change:

 Intent reload = new Intent(getApplicationContext(), TwitterActivity.class);

to

Intent reload = new Intent(TwitterActivity.this, TwitterActivity.class);

EDIT: You need to move your try / catch block into a new method called refresh(). Then call that method anytime you want to reload the list. like this:

It would also be a bood idea to move your networking out of the main thread.

public class TwitterActivity extends ListActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);

    setContentView(R.layout.twitteract);


    Button refresh = (Button) findViewById(R.id.btn_refresh);

    //Listening to button event
    refresh.setOnClickListener(new View.OnClickListener() {

        public void onClick(View arg0) {
            refresh();


        }
    });



    refresh();



}

private void refresh(){

     try{
        // Create a new HTTP Client
        DefaultHttpClient defaultClient = new DefaultHttpClient();
        // Setup the get request
        HttpGet httpGetRequest = new HttpGet("https://api.twitter.com/1/statuses/user_timeline.json?screen_name=evostikleague&count=10");

        // Execute the request in the client
        HttpResponse httpResponse = defaultClient.execute(httpGetRequest);
        // Grab the response
        BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8"));
        String json = reader.readLine();

        Log.v(json,"jsonfeed");




        List<String> items = new ArrayList<String>();

          //items.add(json);


        JSONArray jArray = new JSONArray(json);


        for (int i=0; i < jArray.length(); i++)
        {    JSONObject oneObject = jArray.getJSONObject(i);
            items.add(oneObject.getString("text"));
             Log.i("items", "items");
        }

        setListAdapter ( new ArrayAdapter<String>(this, R.layout.single_item, items));
        ListView list = getListView();
        list.setTextFilterEnabled(true);


        list.setOnItemClickListener(new OnItemClickListener(){

            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                    long arg3) {
                // TODO Auto-generated method stub
                Toast.makeText(getApplicationContext(), ((TextView) arg1).getText(),1000).show();
            }



        });


    } catch(Exception e){
        // In your production code handle any errors and catch the individual exceptions
        e.printStackTrace();
    }




}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.menu, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    if (item.getItemId() == R.id.home) {

        startActivity(new Intent(TwitterActivity.this, HomeActivity.class));

        return(true);
  }


    if (item.getItemId() == R.id.match) {

        startActivity(new Intent(TwitterActivity.this, MatchActivity.class));

        return(true);
  }



    if (item.getItemId() == R.id.teams) {

        startActivity(new Intent(TwitterActivity.this, TeamsActivity.class));

        return(true);
  }



    if (item.getItemId() == R.id.twitter) {

        startActivity(new Intent(TwitterActivity.this, TwitterActivity.class));

        return(true);
  }

    if (item.getItemId() == R.id.info) {

        startActivity(new Intent(TwitterActivity.this, InfoActivity.class));

        return(true);
  }


    return(super.onOptionsItemSelected(item));


}

}

This is more archaic refresh button but I work well in my application.

public void refresh(View view){          //refresh is onClick name
    onRestart();
}

@Override
protected void onRestart() {

    // TODO Auto-generated method stub
    super.onRestart();
    Intent i = new Intent(lala.this, lala.class);  //your class
    startActivity(i);
    finish();

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM