i have a cartactivity and cartadapter, in cartadapter i add increment and decrement for each stuff, and i sum it in total price and total weight and send it to activity ( it worked by passing textview activity from cartactivity to adapteractivity ) and now i want to get seperated quantity for each item to send to database with format Example if item is ( Wallet, Bag, Shoes ) then quanitity that will send to database like this ( 2, 3, 3) 2 represent for wallet and (,) for seperating item quantity, 3 represent bag, and 3 represent shoes. i don't know how to take each quantity and send it in a format like that
have a look on my adapter
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.ToggleButton;
import androidx.annotation.NonNull;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.cepheuen.elegantnumberbutton.view.ElegantNumberButton;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Currency;
import java.util.List;
import java.util.Locale;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicReference;
import app.gify.co.id.R;
import app.gify.co.id.activity.List_Kado;
import app.gify.co.id.modal.MadolCart;
public class AdapterCart extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
ArrayList<MadolCart> carts;
MadolCart mm;
View view;
View viewku;
Context context;
int kuantitas;
String totalname;
int totalBerat, totalharga;
TextView totalhargas, totalberats;
public AdapterCart(ArrayList<MadolCart> carts, Context context, TextView totalhargas, TextView totalberats) {
this.carts = carts;
this.context = context;
this.totalhargas = totalhargas;
this.totalberats = totalberats;
}
public class MyCart extends RecyclerView.ViewHolder {
public ImageView gambar, tambah, kurang;
public TextView harga, nama, quantitas;
public RelativeLayout background, foreground;
public ElegantNumberButton quantity;
public MyCart(#NonNull View itemView) {
super(itemView);
gambar = itemView.findViewById(R.id.gambarcart);
tambah = itemView.findViewById(R.id.tambahcart);
kurang = itemView.findViewById(R.id.kurangcart);
harga = itemView.findViewById(R.id.hargacart);
nama = itemView.findViewById(R.id.namacart);
quantitas = itemView.findViewById(R.id.quantitas);
background = itemView.findViewById(R.id.background);
foreground = itemView.findViewById(R.id.foreground);
quantity = itemView.findViewById(R.id.quantity);
}
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.adapter_cart, parent, false);
viewku = LayoutInflater.from(parent.getContext()).inflate(R.layout.cart, parent, false);
return new MyCart(view);
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, int position) {
kuantitas = carts.get(position).getJumlah();
int hargaku = carts.get(position).getHarga() * kuantitas;
for (int a = 0; a < carts.size(); a++){
Log.d("cartsizeku", "onBindViewHolder: " + carts.size()+ " s " + carts.get(a).getNamacart() + " s " + carts.get(a).getHarga());
String nama = carts.get(position).getNamacart();
if (nama.equals(carts.get(a).getNamacart())){
totalhargas.setText(String.valueOf(totalCart(carts, carts.get(a).getNamacart())));
totalberats.setText(String.valueOf(beratCart(carts, carts.get(a).getNamacart())));
}
}
Locale locale = new Locale("id", "ID");
NumberFormat format = NumberFormat.getCurrencyInstance(locale);
((MyCart)holder).harga.setText(format.format(Double.valueOf(hargaku)));
((MyCart)holder).nama.setText(carts.get(position).getNamacart());
Glide.with(view).load(carts.get(position).getGambar()).into(((MyCart)holder).gambar);
Intent intent = new Intent("message_subject_intent");
// intent.putExtra("name", String.valueOf((totalCart(carts))));
intent.putExtra("title", String.valueOf((getName(carts))));
LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
((MyCart) holder).tambah.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int count = Integer.parseInt(((MyCart) holder).quantitas.getText().toString());
if (count<9){
count+=1;
((MyCart)holder).quantitas.setText(String.valueOf(count));
int harga = carts.get(position).getHarga()*count;
((MyCart)holder).harga.setText(String.valueOf(format.format(Double.valueOf(harga))));
String nama = carts.get(position).getNamacart();
totalhargas.setText(String.valueOf(totalCart(carts, nama)));
totalberats.setText(String.valueOf(beratCart(carts, nama)));
}
// ((MyCart)holder).quantitas.setText(String.valueOf(kuantitas));
int total = hargaku * kuantitas;
Intent intents = new Intent("message_subject_intent");
intents.putExtra("name", String.valueOf((getName(carts))));
LocalBroadcastManager.getInstance(context).sendBroadcast(intents);
}
});
((MyCart) holder).kurang.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int count = Integer.parseInt(((MyCart)holder).quantitas.getText().toString());
if (count>1){
count-=1;
((MyCart)holder).quantitas.setText(String.valueOf(count));
int harga = carts.get(position).getHarga()*count;
((MyCart)holder).harga.setText(String.valueOf(format.format(Double.valueOf(harga))));
String nama = carts.get(position).getNamacart();
totalhargas.setText(String.valueOf(kurangtotalcart(carts, nama)));
totalberats.setText(String.valueOf(kurangberatCart(carts, nama)));
}
// ((MyCart)holder).quantitas.setText(String.valueOf(kuantitas));
int total = hargaku * kuantitas;
Intent intents = new Intent("message_subject_intent");
intents.putExtra("name", String.valueOf((getName(carts))));
LocalBroadcastManager.getInstance(context).sendBroadcast(intents);
}
});
}
#Override
public int getItemCount() {
return carts.size();
}
public int totalCart(ArrayList<MadolCart> items, String name){
for(int i = 0 ; i < items.size(); i++) {
totalname = items.get(i).getNamacart();
if (totalname.equals(name)){
totalharga += items.get(i).getHarga();
}
}
return totalharga;
}
public int kurangtotalcart(ArrayList<MadolCart> items, String name){
for(int i = 0 ; i < items.size(); i++) {
totalname = items.get(i).getNamacart();
if (totalname.equals(name)){
totalharga -= items.get(i).getHarga();
}
}
return totalharga;
}
public int beratCart(ArrayList<MadolCart> items, String name){
for(int i = 0 ; i < items.size(); i++) {
totalname = items.get(i).getNamacart();
if (totalname.equals(name)){
totalBerat += items.get(i).getBerat();
}
}
return totalBerat;
}
public int kurangberatCart(ArrayList<MadolCart> items, String name){
for(int i = 0 ; i < items.size(); i++) {
totalname = items.get(i).getNamacart();
if (totalname.equals(name)){
totalBerat -= items.get(i).getBerat();
}
}
return totalBerat;
}
public String getName(List<MadolCart> name){
String ku = "";
for (int i = 0; i < name.size(); i++){
ku += name.get(i).getNamacart() + ", ";
}
return ku;
}
public void removeItem(int item){
carts.remove(item);
notifyItemRemoved(item);
}
public void restoreItem(MadolCart madolCart, int item){
carts.add(item, madolCart);
notifyItemInserted(item);
}
public void quantityPlus(MadolCart madolCart, int item){
}
}
and this is my activity
package app.gify.co.id.activity;
import android.annotation.SuppressLint;
import android.app.Dialog;
import android.app.FragmentTransaction;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.text.Html;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.SpannedString;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.animation.LinearInterpolator;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.RecyclerView;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.DrawableImageViewTarget;
import com.google.android.material.navigation.NavigationView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.io.InputStream;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Currency;
import java.util.Locale;
import java.util.Random;
import app.gify.co.id.R;
import app.gify.co.id.adapter.AdapterCart;
import app.gify.co.id.modal.MadolCart;
//import app.gify.co.id.thirdparty.GMailSender;
//import app.gify.co.id.thirdparty.SenderAgent;
import app.gify.co.id.widgets.RecyclerTouchDelete;
import static app.gify.co.id.baseurl.UrlJson.DELETECART;
import static app.gify.co.id.baseurl.UrlJson.GETBARANG;
import static app.gify.co.id.baseurl.UrlJson.GETCART;
public class CartActivity extends AppCompatActivity implements RecyclerTouchDelete.RecyclerTouchListener{
Button Checkout, lanjutBelanja;
ImageView backCart;
TextView totalbelanjar, totalberat;
AdapterCart adapterCart;
ArrayList<MadolCart> madolCarts;
String namacart, gambarcart, uidku;
GridLayoutManager glm;
RecyclerView recyclerView;
MainActivity mainActivity;
NavigationView navigationView;
public int hargaku, beratku, kuantitas, lastNumber, idbarang, getHargaAwal;
SharedPreferences preferences;
SharedPreferences.Editor editor;
Spanned templateConvert;
NumberFormat format;
Locale id;
Random random;
String template, idberat, idharga;
private Dialog dialog;
LayoutInflater inflater;
ImageView goku;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.cart);
lanjutBelanja = findViewById(R.id.lanjutBelanjaChart);
lanjutBelanja.setOnClickListener(v -> {
Intent intent = new Intent(getApplicationContext(), List_Kado.class);
startActivity(intent);
});
getHargaAwal = getIntent().getIntExtra("harga", 0);
Log.d("setHarga", getHargaAwal + "");
dialog = new Dialog(CartActivity.this);
inflater = (LayoutInflater)this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.loading, null);
goku = layout.findViewById(R.id.custom_loading_imageView);
goku.animate().rotationBy(360).setDuration(3000).setInterpolator(new LinearInterpolator()).start();
dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
dialog.setCancelable(false);
dialog.setContentView(layout);
dialog.show();
id = new Locale("id", "ID");
format = NumberFormat.getCurrencyInstance(id);
random = new Random();
lastNumber = 0;
for (int k = 0; k < 3; k++){
lastNumber+=(random.nextInt(10)*Math.pow(10, k));
}
backCart = findViewById(R.id.backCartNav);
backCart.setOnClickListener(v -> finish());
Checkout = findViewById(R.id.checkoutChart);
totalbelanjar = findViewById(R.id.totalBelanjaChart);
totalberat = findViewById(R.id.totalBeratChart);
recyclerView = findViewById(R.id.rvChart);
preferences = PreferenceManager.getDefaultSharedPreferences(CartActivity.this);
uidku = preferences.getString("uid", "");
madolCarts = new ArrayList<>();
getCart();
glm = new GridLayoutManager(CartActivity.this, 1);
recyclerView.setLayoutManager(glm);
Checkout.setOnClickListener(view -> {
Intent intent = new Intent(CartActivity.this, CheckoutActivity.class);
intent.putExtra("idharga", idharga);
intent.putExtra("name", namacart);
preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
editor = preferences.edit();
editor.remove("range");
editor.remove("acara");
editor.remove("buat");
editor.apply();
startActivity(intent);
});
LocalBroadcastManager.getInstance(this).registerReceiver(passValue, new IntentFilter("message_subject_intent"));
ItemTouchHelper.SimpleCallback callback = new RecyclerTouchDelete(0, ItemTouchHelper.LEFT, this);
new ItemTouchHelper(callback).attachToRecyclerView(recyclerView);
}
public String LoadData(String inFile) {
String tContents = "";
try {
InputStream stream = getAssets().open(inFile);
int size = stream.available();
byte[] buffer = new byte[size];
stream.read(buffer);
stream.close();
tContents = new String(buffer);
} catch (IOException e) {
// Handle exceptions here
}
return tContents;
}
private String replaceNumberOfAmount(String original, int replace){
return original.substring(0, original.length() - 3) + replace;
}
// private void senderEmail(){
// SenderAgent senderAgent = new SenderAgent("gify.firebase#gmail.com", "Confirmation Transaction Gify", templateConvert, CartActivity.this);
// senderAgent.execute();
// }
private void getCart(){
JsonObjectRequest objectRequest = new JsonObjectRequest(Request.Method.GET, GETCART, null, response -> {
try {
JSONArray array = response.getJSONArray("YukNgaji");
for (int a = 0; a < array.length(); a++){
JSONObject object = array.getJSONObject(a);
String id_tetap = object.getString("id_tetap");
if (id_tetap.equalsIgnoreCase(uidku)){
kuantitas = object.getInt("jumlah");
idbarang = object.getInt("id_barang");
idharga = object.getString("harga");
idberat = object.getString("berat");
getBerat(idbarang);
dialog.dismiss();
}
}
dialog.dismiss();
} catch (JSONException e) {
e.printStackTrace();
}
}, error -> {
Log.d("getcart", "getCart: " + error.getMessage());
});
RequestQueue queue = Volley.newRequestQueue(CartActivity.this);
queue.add(objectRequest);
}
public BroadcastReceiver passValue = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
namacart = intent.getStringExtra("name");
Log.d("hargalast", namacart + "");
namacart = intent.getStringExtra("title");
template = "<h2> Gify Transaction </h2> " +
"<h3> Kamu baru saja melakukan pesanan dengan detail sebagai berikut </h3>"
+ "<p><b> Nama barang: </p></b>"
+ "<p><b> Harga barang" + format.format(Double.valueOf(replaceNumberOfAmount(idharga, lastNumber))) + ". Silahkan transfer dengan tiga digit terakhir yaitu :" + lastNumber + "</p></b>"
+ "<p><b> Jika sudah melakukan pembayaran, silahkan konfirmasi disini </p></b>"
+ "https://api.whatsapp.com/send?phone=082325328732&text=Confirmation%20Text"
+ "<h2>Salam, Gify Team</h2>";
Log.d("hargalast", idharga + lastNumber);
templateConvert = Html.fromHtml(template);
}
};
private void getBerat(int idbarang){
JsonObjectRequest objectRequest = new JsonObjectRequest(Request.Method.GET, GETBARANG, null, response -> {
try {
JSONArray array = response.getJSONArray("YukNgaji");
for (int a = 0; a < array.length(); a++){
JSONObject object = array.getJSONObject(a);
int id_barang = object.getInt("id");
if (idbarang==id_barang){
String gambar = object.getString("photo");
int harga = object.getInt("harga");
String namacart = object.getString("nama");
int berat = object.getInt("berat");
MadolCart madolCart = new MadolCart(gambar, harga, namacart, idbarang, kuantitas, berat);
madolCarts.add(madolCart);
adapterCart = new AdapterCart(madolCarts, CartActivity.this, totalbelanjar, totalberat);
recyclerView.setAdapter(adapterCart);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}, error -> {
Log.d("jsoner", "getBerat: " + error.getMessage());
});
RequestQueue queue = Volley.newRequestQueue(CartActivity.this);
queue.add(objectRequest);
}
#Override
public void onSwipe(RecyclerView.ViewHolder viewHolder, int dir, int pos) {
if (viewHolder instanceof AdapterCart.MyCart){
String name = madolCarts.get(viewHolder.getAdapterPosition()).getNamacart();
MadolCart madolCart = madolCarts.get(viewHolder.getAdapterPosition());
int deleteIndex = viewHolder.getAdapterPosition();
Log.d("taptap", "onSwipe: " + madolCarts.get(viewHolder.getAdapterPosition()).getNamacart());
GETBARANG(madolCarts.get(viewHolder.getAdapterPosition()).getNamacart());
adapterCart.removeItem(viewHolder.getAdapterPosition());
}
}
private void deletecart(String id_barang){
StringRequest stringRequest = new StringRequest(Request.Method.GET, DELETECART+"?idtetap="+uidku+"&idbarang="+id_barang, response -> {
try {
if (response.equalsIgnoreCase("bisa")){
Toast.makeText(CartActivity.this, "Barang telah di hapus", Toast.LENGTH_SHORT).show();
Log.d("bisabarangcart", "GETBARANG: " );
}
}catch (Exception e){
Log.d("ekscartactivity", "deletecart: " + e.getMessage());
}
}, error -> {
Log.d("ernocartdel", "deletecart: " + error.getMessage());
});
RequestQueue queue = Volley.newRequestQueue(CartActivity.this);
queue.add(stringRequest);
}
private void GETBARANG(String namas){
JsonObjectRequest objectRequest = new JsonObjectRequest(Request.Method.GET, GETBARANG,null, response -> {
try {
JSONArray array = response.getJSONArray("YukNgaji");
for (int a = 0; a < array.length(); a++){
JSONObject object = array.getJSONObject(a);
String nama = object.getString("nama");
if (nama.equalsIgnoreCase(namas)){
Log.d("namabarang", "GETBARANG: " + nama + " s " + namas);
String id = object.getString("id");
deletecart(id);
}
}
}catch (Exception e){
Log.d("barangexce", "GETBARANG: " + e.getMessage());
}
}, error -> {
Log.d("errorgetbrng", "GETBARANG: " + error.getMessage());
});
RequestQueue queue = Volley.newRequestQueue(CartActivity.this);
queue.add(objectRequest);
}
}
to make sum of total prices i used this code
public int totalCart(ArrayList<MadolCart> items, String name){
for(int i = 0 ; i < items.size(); i++) {
totalname = items.get(i).getNamacart();
if (totalname.equals(name)){
totalharga += items.get(i).getHarga();
}
}
return totalharga;
}
i put summing code in a method, and call the method on if button + is clicked
if button - is clicked it will call this method
public int kurangtotalcart(ArrayList<MadolCart> items, String name){
for(int i = 0 ; i < items.size(); i++) {
totalname = items.get(i).getNamacart();
if (totalname.equals(name)){
totalharga -= items.get(i).getHarga();
}
}
return totalharga;
}
and now idk how to get seperated quanitity for each position / item in recycler view then send it to activity as format ( 1, 2, 3) (,) mean a seperator for each item
How to get value seperated quantity from recycler view item position?
SOLVED
public String getSeperatedquantity(List<MadolCart> quantity){
String kus = "";
for (int i = 0; i < quantity.size(); i++){
kus += quantity.get(i).getQuantity() + ", ";
}
return kus;
}
I found the solution by adding this:
public String getSeperatedquantity(List<MadolCart> quantity){
String kus = "";
for (int i = 0; i < quantity.size(); i++){
kus += quantity.get(i).getQuantity() + ", ";
}
return kus;
}
I'm using this very useful tutorial (https://github.com/RaghavSood/ProAndroidAugmentedReality) for developing a custom AR app.
It works pretty fine, but when I display markers extracted from a file folder (sometimes) the app gets blocked and restarts from the previous activity.
I suppose it's because of the big number of markers situated in the same point of the screen.
Infact, when I lower the radius, and then showing a littler number of markers, the activity continues to work.
Besides, I've tried to modify the function "getTextWidth()" as many people suggest on the net.
I don't know how to reduce the number of Markers drawn on the same point of the screen (so indipendently from reducing the radius). Can you suggest me something? THANKS A LOT!!!!!
I show you the LocalDataSource.java modified:
package com.example.pointofinterests;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;
import com.example.pointofinterests.R;
import com.example.pointofinterests.IconMarker;
import com.example.pointofinterests.Marker;
/**
* This class should be used as a example local data source. It is an example of
* how to add data programatically. You can add data either programatically,
* SQLite or through any other source.
*
* #author Justin Wetherell <phishman3579#gmail.com>
*/
public class LocalDataSource extends DataSource {
private List<Marker> cachedMarkers = new ArrayList<Marker>();
private static Bitmap icon = null;
public LocalDataSource(Resources res) {
if (res == null) throw new NullPointerException();
createIcon(res);
}
protected void createIcon(Resources res) {
if (res == null) throw new NullPointerException();
icon = BitmapFactory.decodeResource(res, R.drawable.icon);
}
public List<Marker> getMarkers() {
try{
String TestoIDPercorsi = readFileAsString("/sdcard/Epulia/IDPercorsi.txt");
if(TestoIDPercorsi==""){
// DOING NOTHING
}else {
String[] IDPercorso = TestoIDPercorsi.split("#");
for(int l=0; l<IDPercorso.length-1; l++){
String TestoPercorso = readFileAsString("/sdcard/Epulia/Percorso" + IDPercorso[l] + ".txt");
if (TestoPercorso.equals("")){
}else {
ArrayList<String> IDSTEPS2 = new ArrayList<String>();
String[] temp = TestoPercorso.split("#");
for (int j=1; j < temp.length; j++){
Log.d("RIGA_" + j + "_" + IDPercorso[l], temp[j]);
if(temp[j].substring(0,2).contains("P")){//POI
String[] POI = temp[j].split("\\|");
String id = POI[1];
String description = POI[2];
Double lat = Double.parseDouble(POI[3]);
Double lng = Double.parseDouble(POI[4]);
String type = POI[5];
Marker poi = new IconMarker(description, lat,lng, 0, Color.DKGRAY, icon);
cachedMarkers.add(poi);
}
}
}
}
}
}catch (Exception e){
Log.e("EXCEPTION", "> " + e);
}
return cachedMarkers;
}
public static String readFileAsString(String filePath) {
String result = "";
File file = new File(filePath);
if ( file.exists() ) {
FileInputStream fis = null;
try {
fis = new FileInputStream(file);
char current;
while (fis.available() > 0) {
current = (char) fis.read();
result = result + String.valueOf(current);
}
} catch (Exception e) {
Log.d("TourGuide", e.toString());
} finally {
if (fis != null)
try {
fis.close();
} catch (IOException ignored) {
}
}
}
return result;
}
}
I would like to thank the Author of the Tutorial who helped me in fixing the problem.
I report his answer that soled my problem:
Not sure why you have that limitation but this should limit the number of Markers drawn on the screen.
In class AugmentedView.java
You can introduce a new member variable:
private static int MAX_NUM_TO_DRAW = 10;
Then in the method onDraw(Canvas canvas):
You can quit the drawing loop early.
int i=0;
ListIterator<Marker> iter = collection.listIterator(collection.size());
while (iter.hasPrevious() && i<MAX_NUM_TO_DRAW ) {
Marker marker = iter.previous();
marker.draw(canvas);
i++;
}
I have made a random Image Gallery view with the Android Touch Gallery but I want to Show random Images. I have tried to generate an link with an random number.
I can not Play it and I have no idea how i can solve this.
Please Help.
Activity:
package com.ddd.fun1234;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import ru.truba.touchgallery.GalleryWidget.GalleryViewPager;
import ru.truba.touchgallery.GalleryWidget.UrlPagerAdapter;
import ru.truba.touchgallery.GalleryWidget.BasePagerAdapter.OnItemChangeListener;
import android.app.Activity;
import android.graphics.Bitmap;
import android.os.Bundle;
public class GalleryUrlAvtivity extends Activity {
private GalleryViewPager mViewPager;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public Bitmap GetImage() {
Random rn = new Random();
int n = 200000 - 199000 + 1;
int i = rn.nextInt() % n;
URL tempURL = null;
try {
tempURL = new URL("http://miniz.co/RageToonApp/Images/" + rn + ".jpg");
} catch (MalformedURLException e1) {
e1.printStackTrace();
}
List<String> items = new ArrayList<String>();
Collections.addAll(items, tempURL);
UrlPagerAdapter pagerAdapter = new UrlPagerAdapter(this, items);
pagerAdapter.setOnItemChangeListener(new OnItemChangeListener()
{
#Override
public void onItemChange(int currentPosition)
{
}
});
mViewPager = (GalleryViewPager)findViewById(R.id.viewer);
mViewPager.setOffscreenPageLimit(3);
mViewPager.setAdapter(pagerAdapter);
}
}
There is a fail in Collections.addAll. What can I use instead of this?
When you have an idea what i can do or what is a good second Option, please write it.
Daniel
The problem is in these lines:
Random rn = new Random();
...
int i = rn.nextInt() % n;
...
tempURL = new URL("http://miniz.co/RageToonApp/Images/" + rn + ".jpg");
You are calculating i but instead of using it in the URL, you're using rn instead. By default, this calls Random.toString() which contains characters (in this case, a #) that are illegal in URLs.
To fix this you should change the last line to:
tempURL = new URL("http://miniz.co/RageToonApp/Images/" + i + ".jpg");
We are building an app that is supposed to do several things based on an input text file. First it parses the data in the text file and extracts the useful information and builds a linkedList. The Linked List is a group of BinaryBlock objects. From there we want to dynamically graph the getwfs() function of the BinaryBlocks. At this point, we have got the graph somewhat working but instead of graphing over time it graphs in one big clump and scrolls all the way to the end.
BinaryBlock is listed here:
This is fully tested and functional and really only important in the larger context of the program:
// BinaryBlock.java
public class BinaryBlockLite {
private int pwda[], wfs[];
String lineData;
public BinaryBlockLite( String data ){ // class constructor
lineData = data;
pwda = new int[5];
wfs = new int[4];
setWfs();
}//end constructor
public String WfsToString(){
if (wfs.length == 0)
return "";
String data = "Channel 2: ";
for(int i = 0; i < wfs.length; ++i ){
data = data + "wfs[" + i + "]=" + wfs[i] + " ";
}
return data + "\n";
}
//===========================================================
// Setters
//=============================================================
//read the 5 individual bytes of the Pwda from LineData and into the pwda[] array
private void setPwda(){
int location = 13;
for(int i = 0; i < 5; ++i){
String temp = "" + lineData.charAt(++location) + lineData.charAt(++location);
pwda[i] = Integer.parseInt(temp, 16);
}
}
//logically manipulate the 5 bytes of the PWDA into 4 10-bit WFSs
private void setWfs(){
setPwda();
int j = 0;
for (int i = 0; i < 4; ++i){
wfs[i] = ((pwda[j] << 2) | (( pwda[j + 1] >> 6) & 0x03)) & 0x03ff;
wfs[++i] = ((pwda[j + 1] << 4) | (( pwda[j + 2] >>> 4) & 0x0f)) & 0x03ff;
wfs[++i] = ((pwda[j + 2] << 6) | (( pwda[j + 3] >>> 2) & 0x3f)) & 0x03ff;
wfs[++i] = ((pwda[j + 3] << 8) | (( pwda[j + 4] >>> 0) & 0xff)) & 0x03ff;
}
}
//===========================================================
// Getters
//=============================================================
public int[] getPwda(){
return pwda;
}
public int[] getWfs(){
return wfs;
}
}//end BinaryBlock Class
The main harness is listed here:
The problem is simply that instead of repainting each time and graphing it across the screen, it graphs all of the point at one time.
//MainActivity.java
import android.os.Bundle;
import android.app.ActionBar.LayoutParams;
import android.app.Activity;
import android.content.Context;
import android.content.res.AssetManager;
import android.graphics.Color;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import com.smith.fsu.wave.BinaryBlockLite;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.ListIterator;
import org.achartengine.ChartFactory;
import org.achartengine.GraphicalView;
import org.achartengine.model.XYMultipleSeriesDataset;
import org.achartengine.model.XYSeries;
import org.achartengine.renderer.XYMultipleSeriesRenderer;
import org.achartengine.renderer.XYSeriesRenderer;
public class MainActivity extends Activity {
public static LinkedList<BinaryBlockLite> list;
Button btnMain;
Boolean fileLoaded = false;
int xTick = 0,
lastMinX = 0;
Context context = this;
//
////////////////////////////////////////////////////////////////
//import test
private XYMultipleSeriesDataset WFDataset = new XYMultipleSeriesDataset();
private XYMultipleSeriesRenderer WaveFormRenderer = new XYMultipleSeriesRenderer();
private XYSeries WFCurrentSeries;
private GraphicalView WFChartView;
//////////////////////////////////////////////////////////////////////////
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list = new LinkedList<BinaryBlockLite>();
btnMain=(Button)findViewById(R.id.btnMain);
WaveFormRenderer.setAxisTitleTextSize(16);
WaveFormRenderer.setChartTitleTextSize(20);
WaveFormRenderer.setLabelsTextSize(15);
WaveFormRenderer.setLegendTextSize(15);
WaveFormRenderer.setMargins(new int[] {20, 30, 15, 0});
WaveFormRenderer.setAxesColor(Color.YELLOW);
String seriesTitle = "Input Data";
XYSeries series = new XYSeries(seriesTitle);
WFDataset.addSeries(series);
WFCurrentSeries = series;
XYSeriesRenderer renderer = new XYSeriesRenderer();
renderer.setColor(Color.GREEN);
WaveFormRenderer.addSeriesRenderer(renderer);
WaveFormRenderer.setXAxisMin(0.0);
WaveFormRenderer.setXAxisMax(500);
// renderer.setFillBelowLine(true) ;
// renderer.setFillBelowLineColor(Color.BLUE);
}
public void chartClick(View view) throws IOException{
String strData = "";
AssetManager amInput = context.getAssets();
BufferedReader reader;
InputStream is = null;
try {
is = amInput.open("Dinamap-Data.txt");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
reader = new BufferedReader(new InputStreamReader(is));
try {
while( (strData = reader.readLine()) != null ) {
addBlock( strData ); //call to paint line
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}//while loop
try {
reader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}//end mainClick() method for btnMain
public void writeClick(View view){
//write decimal data for wfs out to file from LinkedList<BinaryBlock>
//using WfsToString() method of BinaryBlock class in separate thread
(new Thread(new Runnable() {
#Override
public void run() {
FileOutputStream fos = null;
try {
fos = openFileOutput("wfs.txt", Context.MODE_WORLD_READABLE);
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
ListIterator<BinaryBlockLite> itr = list.listIterator();
while (itr.hasNext()){
String temp = itr.next().WfsToString();
try {
fos.write(temp.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
}
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
})).start();
btnMain.setEnabled(false);
}
private void addBlock(final String strData) {
new Thread(new Runnable() {
public void run() {
int wfs[];
//read line into binaryBlockLite object and store object in Linked List
BinaryBlockLite bb = new BinaryBlockLite(strData);
list.add(bb);
//get the wfs data from the BinaryBlockLite object
wfs = new int[bb.getWfs().length];
wfs = bb.getWfs();
//grab each wfs individually and paint to the chart, and increment xTick
for (int k = 0; k < wfs.length; ++k){
/* check if we need to shift the x axis */
if (xTick > WaveFormRenderer.getXAxisMax()) {
WaveFormRenderer.setXAxisMax(xTick);
WaveFormRenderer.setXAxisMin(++lastMinX);
}
if (wfs[k] > 1000){
WFCurrentSeries.add(xTick, WFCurrentSeries.getY(xTick - 1));
}
else{
WFCurrentSeries.add(xTick, wfs[k]);
}
++xTick;
}
WFChartView.repaint();
}
}).start();
}
#Override
protected void onResume() {
super.onResume();
if (WFChartView == null) {
LinearLayout layout = (LinearLayout) findViewById(R.id.WFchart);
WFChartView = ChartFactory.getLineChartView(this, WFDataset, WaveFormRenderer);
layout.addView(WFChartView, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
// boolean enabled = WFDataset.getSeriesCount() > 0;
// setSeriesEnabled(enabled);
} else {
WFChartView.repaint();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
I think it's either super simple or a threading issue which is something that I haven't played with enough. Any help would be appreciated.
Looking at the code, I see that you add all the data to the series and then call repaint.
If you want the data to be gradually added, then move the repaint inside the for loop and put a Thread.sleep() inside, to give a chance to the UI thread to actually do the repaint.
I am planning to create a world clock widget in android. The clock should show the selected country's time as an analog clock widget. But I'm feeling difficulties as I'm a beginner in android.
My widget.xml file contains the following:-
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/Widget"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_margin="8dip"
android:background="#drawable/myshape" >
<AnalogClock android:id="#+id/AnalogClock"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:dial="#drawable/widgetdial"
android:hand_hour="#drawable/widgethour"
android:hand_minute="#drawable/widgetminute"/>
I am using the following configuration activity for my widget:-
(To display the city list)
package nEx.Software.Tutorials.Widgets.AnalogClock;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Calendar;
import android.app.Activity;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.appwidget.AppWidgetManager;
import android.content.Intent;
import android.os.Bundle;
import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AnalogClock;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RemoteViews;
import android.widget.TextView;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
public class ConfigureApp extends Activity {
DateFormat df;
private ListView cityList;
public static String[][] citylist = new String[1242][10];
String[] cities = new String[1242];
String field[] = new String[20];
String list[][] = new String[1242][10];
String country = "";
String line = null;
int row = 0;
int col = 0;
// Variables for list view population
String city = "";
int position = 0;
public int[] listArray = new int[1242];
public static int len = 0;
public String[][] adapterCityList = new String[1242][3];
// Variables for passing intent data
public static final String citieslist = "com.world.citieslist";
AppWidgetManager awm;
Context c;
int awID;
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
// Set the result to CANCELED. This will cause the widget host to cancel
// out of the widget placement if they press the back button.
setResult(RESULT_CANCELED);
try {
citylist = getCityList();
} catch (IOException e) {
Log.e("Loading CityList", e.getMessage());
}
for (int i = 0; i < 1242; i++) {
cities[i] = citylist[i][0];
}
// Set the view layout resource to use.
setContentView(R.layout.configure);
c = ConfigureApp.this;
Intent intent = getIntent();
Bundle extras = intent.getExtras();
if (extras != null) {
awID = extras.getInt(
AppWidgetManager.EXTRA_APPWIDGET_ID,
AppWidgetManager.INVALID_APPWIDGET_ID);
} else{
finish();
}
awm = AppWidgetManager.getInstance(c);
cityList=(ListView)findViewById(R.id.CityList);
// By using setAdpater method in listview we an add string array in list.
cityList.setAdapter(new ArrayAdapter<String> (this,android.R.layout.simple_list_item_1, cities));
// cityList.setOnItemClickListener(cityListListener);
cityList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> av, View v, int pos, long id) {
df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
String str = ((TextView) v).getText().toString();
RemoteViews remoteViews = new RemoteViews(c.getPackageName(),
R.layout.widget);
remoteViews.setTextViewText(R.id.mytext, str);
remoteViews.setTextViewText(R.id.date, df.format(new Date()));
Intent in = new Intent(c,clock.class);
PendingIntent pi = PendingIntent.getActivity(c, 0, in, 0);
remoteViews.setOnClickPendingIntent(R.id.Widget, pi);
awm.updateAppWidget(awID, remoteViews);
Intent result = new Intent();
result.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID,awID);
setResult(RESULT_OK, result);
finish();
}
});
}
private String[][] getCityList() throws IOException {
Context context = getApplicationContext();
InputStream instream = context.getResources().openRawResource(R.raw.cities_final);
// if file the available for reading
if (instream != null) {
// prepare the file for reading
InputStreamReader inputreader = new InputStreamReader(instream);
BufferedReader buffreader = new BufferedReader(inputreader);
while ((line = buffreader.readLine()) != null) {
field = line.split(",");
for (String x : field) {
list[row][col] = x;
col++;
if (x != null) {
country = x;
}
}
list[row][2] = country;
row++;
col = 0;
}
for (int i = 0; (i < list.length); i++) {
for (int j = 0; (j < 3); j++) {
if (j == 1) {
list[i][j] = list[i][j].substring(0, 6);
}
}
}
}
return list;
}
}
Can I use my own custom view in the widget, apart from analog clock? Or is there any other way to show the clock? like use the Imageview as the clock face and to draw the dial according to the time?
Please help me regarding this.!!!:(
A similar example for thermometer is given in this link
http://mindtherobot.com/blog/272/android-custom-ui-making-a-vintage-thermometer/
You can create your own view and make the clock as well.
You can replaced the clock dial, clock hand minute and clock hand hour with your own drawings. Then You'll have your own custom clock.
android:dial="#drawable/YOUR_OWN_DIAL"
android:hand_hour="#drawable/YOUR_OWN_HOUR"
android:hand_minute="#drawable/YOUR_OWN_MINUTE"
Test the layout in the Graphical Layout Tool to see how it look like.