Передача данных метода другому методу в том же Activity - PullRequest
0 голосов
/ 26 сентября 2018

Я новичок в Android Studio, и я делаю свой последний проект года.

Я сделал сканер QR-кода, который может извлекать данные из HTTP с помощью Rest API.

Мой вопрос: Мне нужно отправить все данные JSON в другой вид деятельности, основываясь на моих исследованиях, мне нужно намерить свою кнопку, потому что мне нужно передать мой JsonRequestданные в Btn_BuyClicked метод, чтобы я мог отправить все эти к следующему действию.

Я использовал AndroidHive MovieTickets, чтобы я не менял столько кода.

Пожалуйста, помогите мне.Спасибо.

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);
}

}

Это мой класс TicketResultActivity.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);
}

} ​​

Это Test.java Класс

public class Test extends Activity {


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_test);

        Movie movie = (Movie) getIntent().getParcelableExtra("parcel_data");
        String apa_number = movie.getApa_number();

        TextView textView1 = findViewById(R.id.textView2);
        textView1.setText(apa_number);
    }

}

Ответы [ 2 ]

0 голосов
/ 26 сентября 2018

Существует так много способов отправки данных из одного действия в другое.Если у вас есть данные типа Primitive или Json string, вы можете напрямую поместить эти данные в намерение.

Но если в этом случае у вас есть класс Model, и вам нужно его передать.Тогда у вас есть два пути:

  1. Сериализуемый
  2. Parcelable

Но Android рекомендуемиспользовать Parcelable.

Вы также можете добавить плагин в android studio для генерации кода распаковки.

0 голосов
/ 26 сентября 2018
        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();
        }
        }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...