将方法数据传递到同一Activity中的其他方法

时间:2018-09-26 11:09:49

标签: json android-studio android-intent

我是Android Studio的新手,正在做我的最后一年的项目。

我制作了一个QR码扫描仪,可以使用Rest API从HTTP检索数据。

我的问题是:我需要将所有JSON数据发送到其他活动,根据我的研究,我需要将意图放在按钮上,因为这需要将JsonRequest数据传递给// router.js import Vue from "vue" import Router from "vue-router" import App from './App.vue' import List from './List.vue' Vue.use(Router) const routes = [ {path: '/list', component: List, props: users}, {path: '*', redirect: '/list'} ] export default new Router({ routes: routes }) 方法,这样我就可以将所有这些发送给下一个活动。

我使用了AndroidHive MovieTickets,因此我并没有改变太多的编码。

请帮助我。谢谢。

Btn_BuyClicked

}

这是我的TicketResultActivity.java类更新的代码

public class TicketResultActivity extends AppCompatActivity {
private static final String TAG = TicketResultActivity.class.getSimpleName();

private Button btnBuy;
private ImageView imgPoster;
private ProgressBar progressBar;
private TicketView ticketView;
private TextView txtDirector;
private TextView txtYear_created;
private TextView txtError;
private TextView txtType_powder;
private TextView txtApa_number;
private TextView txtLocation;
private TextView txtDate_expired;

private Button signOut;
private FirebaseAuth auth;

private class Movie {
    String director;
    String year_created;
    String type_powder;
    @SerializedName("released")
    boolean isReleased;
    String apa_number;
    String poster;
    String location;
    String date_expired;

    private Movie() {
    }

    public String getApa_number() {
        return this.apa_number;
    }

    public String getDirector() {
        return this.director;
    }

    public String getPoster() {
        return this.poster;
    }

    public String getYear_created() {
        return this.year_created;
    }

    public String getType_powder() {
        return this.type_powder;
    }

    public String getLocation() {
        return this.location;
    }

    public String getDate_expired() {
        return this.date_expired;
    }

    public boolean isReleased() {
        return this.isReleased;
    }
}

NotificationCompat.Builder notification;
private static final int uniqueID = 250298;


protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_ticket_result);
    setSupportActionBar((Toolbar) findViewById(R.id.toolbar));
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    this.txtApa_number = (TextView) findViewById(R.id.apa_number);
    this.txtDirector = (TextView) findViewById(R.id.director);
    this.txtYear_created = (TextView) findViewById(R.id.year_created);
    this.txtLocation = (TextView) findViewById(R.id.location);
    this.txtDate_expired = (TextView) findViewById(R.id.date_expired);
    this.imgPoster = (ImageView) findViewById(R.id.poster);
    this.txtType_powder = (TextView) findViewById(R.id.type_powder);
    this.btnBuy = (Button) findViewById(R.id.btn_buy);
    this.imgPoster = (ImageView) findViewById(R.id.poster);
    this.txtError = (TextView) findViewById(R.id.txt_error);
    this.ticketView = (TicketView) findViewById(R.id.layout_ticket);
    this.progressBar = (ProgressBar) findViewById(R.id.progressBar);
    String barcode = getIntent().getStringExtra("code");
    if (TextUtils.isEmpty(barcode)) {
        Toast.makeText(getApplicationContext(), "Barcode is empty!", Toast.LENGTH_LONG).show();
        finish();
    }
    searchBarcode(barcode);

}




public void btn_buyClicked(View view) {

    notification.setSmallIcon(R.drawable.qrcode);
    notification.setTicker("This is the ticker");
    notification.setWhen(System.currentTimeMillis());
    notification.setContentTitle("Fire Extinguisher Scanner");



    Intent intent = new Intent(this, Test.class);
    startActivity(new Intent(TicketResultActivity.this, Test.class));
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    notification.setContentIntent(pendingIntent);

    NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    nm.notify(uniqueID, notification.build());


}


private void searchBarcode(String barcode) {
    MyApplication.getInstance().addToRequestQueue(new JsonObjectRequest(Request.Method.GET,  barcode, null, new Listener<JSONObject>() {
        public void onResponse(JSONObject response) {
            Log.e(TicketResultActivity.TAG, "Ticket response: " + response.toString());
            if (response.has("error")) {
                TicketResultActivity.this.showNoTicket();
            } else {
                TicketResultActivity.this.renderMovie(response);

            }
        }
    }, new ErrorListener() {
        public void onErrorResponse(VolleyError error) {
            Log.e(TicketResultActivity.TAG, "Error: " + error.getMessage());
            TicketResultActivity.this.showNoTicket();
        }
    }));
}

private void showNoTicket() {
    this.txtError.setVisibility(View.VISIBLE);
    this.ticketView.setVisibility(View.GONE);
    this.progressBar.setVisibility(View.GONE);
}



public void renderMovie(JSONObject response) {
    try {
        Movie movie = (Movie) new Gson().fromJson(response.toString(), Movie.class);
        if (movie != null) {
            this.txtApa_number.setText(movie.getApa_number());
            this.txtDirector.setText(movie.getDirector());
            this.txtYear_created.setText(movie.getYear_created());
            this.txtType_powder.setText(movie.getType_powder());
            this.txtDate_expired.setText(BuildConfig.FLAVOR + movie.getDate_expired());
            this.txtLocation.setText(movie.getLocation());
            Glide.with(this).load(movie.getPoster()).into(this.imgPoster);
            notification.setContentText("Fire Extinguisher "+ movie.getApa_number()+"successfully remind!");


            if (movie.isReleased()) {
                this.btnBuy.setText(getString(R.string.btn_buy_now));
                this.btnBuy.setTextColor(ContextCompat.getColor(this, R.color.colorPrimary));
            } else {
                this.btnBuy.setText(getString(R.string.btn_buy_now));
                this.btnBuy.setTextColor(ContextCompat.getColor(this, R.color.colorPrimary));
            }
            this.ticketView.setVisibility(View.VISIBLE);
            this.progressBar.setVisibility(View.GONE);
            return;
        }
        showNoTicket();
    } catch (JsonSyntaxException e) {
        Log.e(TAG, "JSON Exception: " + e.getMessage());
        showNoTicket();
        Toast.makeText(getApplicationContext(), "Error occurred. Check your LogCat for full report", Toast.LENGTH_SHORT).show();
    } catch (Exception e2) {
        showNoTicket();
        Toast.makeText(getApplicationContext(), "Error occurred. Check your LogCat for full report", Toast.LENGTH_SHORT).show();
    }
}

public boolean onOptionsItemSelected(MenuItem item) {
    if (item.getItemId() == android.R.id.home) {
        finish();
    }
      return super.onOptionsItemSelected(item);
}

}

这是 Test.java类

 private static class Movie implements Parcelable {
    String director;
    String year_created;
    String type_powder;
    @SerializedName("released")
    boolean isReleased;
    String apa_number;
    String poster;
    String location;
    String date_expired;

    public Movie() {

    }


    public Movie(Parcel in) {
        director = in.readString();
        year_created = in.readString();
        type_powder = in.readString();
        isReleased = in.readByte() != 0;
        apa_number = in.readString();
        poster = in.readString();
        location = in.readString();
        date_expired = in.readString();
    }


    public String getApa_number(){
        return this.apa_number;
    }

    public String getYear_created() {
        return year_created;
    }

    public String getType_powder() {
        return type_powder;
    }

    public String getDirector() {
        return director;
    }

    public String getPoster() {
        return poster;
    }

    public String getLocation() {
        return location;
    }

    public boolean isReleased() {
        return isReleased;
    }

    public String getDate_expired() {
        return date_expired;
    }

    public void setApa_number(String apa_number){
        this.apa_number = apa_number;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(director);
        dest.writeString(year_created);
        dest.writeString(type_powder);
        dest.writeByte((byte) (isReleased ? 1 : 0));
        dest.writeString(apa_number);
        dest.writeString(poster);
        dest.writeString(location);
        dest.writeString(date_expired);
    }

    public static final Parcelable.Creator<Movie> CREATOR = new Parcelable.Creator<Movie>() {
        @Override
        public Movie createFromParcel(Parcel in) {
            return new Movie(in);
        }

        @Override
        public Movie[] newArray(int size) {
            return new Movie[size];
        }
    };


    @Override
    public int describeContents() {
        return 0;
    }


}

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_ticket_result);
    setSupportActionBar((Toolbar) findViewById(R.id.toolbar));
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    this.txtApa_number = (TextView) findViewById(R.id.apa_number);
    this.txtDirector = (TextView) findViewById(R.id.director);
    this.txtYear_created = (TextView) findViewById(R.id.year_created);
    this.txtLocation = (TextView) findViewById(R.id.location);
    this.txtDate_expired = (TextView) findViewById(R.id.date_expired);
    this.imgPoster = (ImageView) findViewById(R.id.poster);
    this.txtType_powder = (TextView) findViewById(R.id.type_powder);
    this.btnBuy = (Button) findViewById(R.id.btn_buy);
    this.imgPoster = (ImageView) findViewById(R.id.poster);
    this.txtError = (TextView) findViewById(R.id.txt_error);
    this.ticketView = (TicketView) findViewById(R.id.layout_ticket);
    this.progressBar = (ProgressBar) findViewById(R.id.progressBar);
    String barcode = getIntent().getStringExtra("code");
    if (TextUtils.isEmpty(barcode)) {
        Toast.makeText(getApplicationContext(), "Barcode is empty!", Toast.LENGTH_LONG).show();
        finish();
    }
    searchBarcode(barcode);
}




public void btn_buyClicked(View view) {


    // In activity or fragment
    Movie movie = new Movie();
    movie.setApa_number("xyz");
    Intent intent = new Intent(this, Test.class);
    intent.putExtra("parcel_data", movie);
    startActivity(intent);

}


private void searchBarcode(String barcode) {
    MyApplication.getInstance().addToRequestQueue(new JsonObjectRequest(Request.Method.GET,  barcode, null, new Listener<JSONObject>() {
        public void onResponse(JSONObject response) {
            Log.e(TicketResultActivity.TAG, "Ticket response: " + response.toString());
            if (response.has("error")) {
                TicketResultActivity.this.showNoTicket();
            } else {
                TicketResultActivity.this.renderMovie(response);

            }
        }
    }, new ErrorListener() {
        public void onErrorResponse(VolleyError error) {
            Log.e(TicketResultActivity.TAG, "Error: " + error.getMessage());
            TicketResultActivity.this.showNoTicket();
        }
    }));
}

private void showNoTicket() {
    this.txtError.setVisibility(View.VISIBLE);
    this.ticketView.setVisibility(View.GONE);
    this.progressBar.setVisibility(View.GONE);
}



public void renderMovie(JSONObject response) {
    try {
        Movie movie = (Movie) new Gson().fromJson(response.toString(), Movie.class);
        if (movie != null) {
            this.txtApa_number.setText(movie.getApa_number());
            this.txtDirector.setText(movie.getDirector());
            this.txtYear_created.setText(movie.getYear_created());
            this.txtType_powder.setText(movie.getType_powder());
            this.txtDate_expired.setText(BuildConfig.FLAVOR + movie.getDate_expired());
            this.txtLocation.setText(movie.getLocation());
            Glide.with(this).load(movie.getPoster()).into(this.imgPoster);


            if (movie.isReleased()) {
                this.btnBuy.setText(getString(R.string.btn_buy_now));
                this.btnBuy.setTextColor(ContextCompat.getColor(this, R.color.colorPrimary));
            } else {
                this.btnBuy.setText(getString(R.string.btn_buy_now));
                this.btnBuy.setTextColor(ContextCompat.getColor(this, R.color.colorPrimary));
            }
            this.ticketView.setVisibility(View.VISIBLE);
            this.progressBar.setVisibility(View.GONE);
            return;
        }
        showNoTicket();
    } catch (JsonSyntaxException e) {
        Log.e(TAG, "JSON Exception: " + e.getMessage());
        showNoTicket();
        Toast.makeText(getApplicationContext(), "Error occurred. Check your LogCat for full report", Toast.LENGTH_SHORT).show();
    } catch (Exception e2) {
        showNoTicket();
        Toast.makeText(getApplicationContext(), "Error occurred. Check your LogCat for full report", Toast.LENGTH_SHORT).show();
    }
}

public boolean onOptionsItemSelected(MenuItem item) {
    if (item.getItemId() == android.R.id.home) {
        finish();
    }
      return super.onOptionsItemSelected(item);
}

}

2 个答案:

答案 0 :(得分:0)

        Use Parcelable is an interface. A class who implements Parcelable can write to and read from a Parcel.
        You need to follow 3 points to create a Parcelable class.
        A Class must implement Parcelable interface
        A Class must have a non-null static field CREATOR of a type that implements Parcelable.Creator interface.
        Override writeToParcel method and write member variable in Parcel. Make sure to read variables in the same sequence in which they are written in Parcel. Order of read and write matters.


        private class Movie implements Parcelable{
            String director;
            String year_created;
            String type_powder;
            @SerializedName("released")
            boolean isReleased;
            String apa_number;
            String poster;
            String location;
            String date_expired;

    public Movie() {

    }

            // In constructor you will read the variables from Parcel. Make sure to read them in the same sequence in which you have written them in Parcel.
        public Movie(Parcel in) {
        director = in.readString();
        year_created = in.readString();
        release_date = in.readString();
        poster = in.readString();
        }

            public String getApa_number() {
                return this.apa_number;
            }

             public String getDirector() {
        return director;
    }

    public void setDirector(String director) {
        this.director = director;
    }

        // This is where you will write your member variables in Parcel. Here you can write in any order. It is not necessary to write all members in Parcel.
        @Override
        public void writeToParcel(Parcel dest, int flags) {
        // Write data in any order
        dest.writeString(director);
        dest.writeString(year_created);
        dest.writeString(release_date);
        dest.writeString(poster);
        }

        // This is to de-serialize the object
        public static final Parcelable.Creator<Movie> CREATOR = new Parcelable.Creator<Movie>(){
        public Movie createFromParcel(Parcel in) {
        return new Movie(in);
        }

        public Movie[] newArray(int size) {
        return new Movie[size];
        }
        };
        }

        Now you can pass a Parcelable object using Intent.

        // In activity or fragment
        Movie movie = new Movie();
movie.setDirector("xyz");
// now you can set all values like :year created, is released whatever.
        // using context and next component class to create intent
        Intent intent = new Intent(this, NextActivity.class);
        // using putExtra(String key, Parcelable value) method
        intent.putExtra(“parcel_data”, movie);
        startActivity(intent);

        You can access this data in NextActivity –

        public class NextActivity extends Activity {
        @Override
        protected void onCreate(Bundle savedInstanceState) {
        // Using getParcelableExtra(String key) method
        Movie movie = (Movie) getIntent().getParcelableExtra("parcel_data");
           String director = movie.getDirector();
        }
        }

答案 1 :(得分:0)

有许多种方法可以将数据从一个活动发送到另一个活动。如果您拥有PrimitiveJson string类型的数据,则可以直接将该数据放入意图中。

但是如果您有Model类,则需要传递它。然后您有两种方法:

  1. Serializable
  2. Parcelable

但是Android建议使用Parcelable。

您还可以将插件添加到android studio中以生成可打包代码。