Dear All I use PagerView to make a slider images and every thing went well
if I use a URL images and String array from drawable images.
But when I use a file stored in my APP directory its not work you will see my code here
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<android.support.v4.view.ViewPager
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/viewPager"/>
</android.support.constraint.ConstraintLayout>
image_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="#+id/imageView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
app:srcCompat="#mipmap/ic_launcher" />
</LinearLayout>
BitmapPagerAdapter.java
package com.samcotec.pager2;
import android.content.Context;
import android.graphics.Bitmap;
import android.support.v4.view.PagerAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.List;
public class BitmapPagerAdapter extends PagerAdapter {
Context context;
ArrayList<Bitmap> bitmaps;
LayoutInflater layoutInflater;
public BitmapPagerAdapter(Context context, ArrayList<Bitmap> bitmaps){
this.context = context;
this.bitmaps = bitmaps;
layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return bitmaps.size();
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
#Override
public Object instantiateItem(ViewGroup container, final int position){
View itemView = layoutInflater.inflate(R.layout.image_layout, container, false);
ImageView imageView = (ImageView) itemView.findViewById(R.id.imageView);
imageView.setImageBitmap(bitmaps.get(position));
container.addView(itemView);
//listening to image click
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, "you clicked image " + (position + 1), Toast.LENGTH_LONG).show();
}
});
return itemView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((LinearLayout) object);
}
}
MainActivity.java
package com.samcotec.pager2;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
ArrayList<Bitmap> bitmap = new ArrayList<Bitmap>();
ViewPager viewPager;
BitmapPagerAdapter bitmapPagerAdapter;
String imgPath;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imgPath = "/data/data/" + this.getPackageName() + "/" + "quranIMG/";
File savefliepath = new File(imgPath);
if(!savefliepath.exists()){
System.out.println("file not exist: " + imgPath);
savefliepath.mkdir();
}else{
//System.out.println("file exist: " + imgPath);
}
final AssetManager assetManager = getAssets();
String[] list;
InputStream f;
String FileName;
String URLPATH = "http://192.168.100.12/quran/";
Integer StartFrom = 100;
Integer EndTo = 150;
for(int i = StartFrom; i <= EndTo; i++){
FileName = "a-("+i+").png";
File savefile = new File(imgPath + FileName);
if(!savefile.exists()){
// tools.copyAssets(assetManager,Path);
DownloadTask downloadTask = new DownloadTask(URLPATH,imgPath,FileName);
}else{
}
// imgList.add(i);
}
// TODO : we must check internet connection if its ok
for (int i = StartFrom; i<EndTo; i++){
String b = imgPath + "a-("+i+").png";
// System.out.println("file exists" + b);
FileInputStream fiStream;
File imgFile = new File(getFilesDir(), b);
Bitmap bit;
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 4;
if(imgFile.exists()){
try{
fiStream = MainActivity.this.openFileInput(b);
bit = BitmapFactory.decodeStream(fiStream);
bitmap.add(bit);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}else{
DownloadTask downloadTask = new DownloadTask(URLPATH,imgPath,"a-("+i+").png");
File imgFile1 = new File(getFilesDir(), b);
if(imgFile1.exists()) {
try{
fiStream = MainActivity.this.openFileInput(b);
bit = BitmapFactory.decodeStream(fiStream);
bitmap.add(bit);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}else{
bit = null;
}
}
}
viewPager = (ViewPager) findViewById(R.id.viewPager);
bitmapPagerAdapter = new BitmapPagerAdapter(MainActivity.this,bitmap);
viewPager.setAdapter(bitmapPagerAdapter);
}
}
I user some tools to download files and store it in imgPath
Images is downloaded and stored and no issue for it
but the issue that
bitmap.size();
always empty and the APP Crashed
The problem is in my DownloadTask not in the code itself.
I solve it by changing the download task to code:
package com.samcotec.pager2;
import android.widget.Toast;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
public class DownloadTask {
public DownloadTask(final String url, final String savePath, final String saveName) {
new Thread(new Runnable() {
public void run() {
try {
System.out.println(url+saveName);
URL sourceUrl = new URL(url+saveName);
URLConnection conn = sourceUrl.openConnection();
conn.connect();
InputStream inputStream = conn.getInputStream();
int fileSize = conn.getContentLength();
File savefilepath = new File(savePath);
if (!savefilepath.exists()) {
savefilepath.mkdirs();
}
File savefile = new File(savePath+saveName);
if (savefile.exists()) {
savefile.delete();
}
savefile.createNewFile();
FileOutputStream outputStream = new FileOutputStream(savePath+saveName, true);
byte[] buffer = new byte[1024];
int readCount = 0;
int readNum = 0;
int prevPercent = 0;
while (readCount < fileSize && readNum != -1) {
readNum = inputStream.read(buffer);
if (readNum > -1) {
outputStream.write(buffer, 0, readNum);
readCount = readCount + readNum;
int percent = (int) (readCount * 100 / fileSize);
if (percent > prevPercent) {
System.out.println(percent);
//Toast.makeText(LoadPage.MY_CONTEXT,percent,Toast.LENGTH_LONG);
prevPercent = percent;
}
}
}
outputStream.flush();
outputStream.close();
inputStream.close();
//Thread.sleep(50);
} catch (Exception e) {
System.out.println( e);
}
}
}).start();
}
}
Related
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 am having an arrayList of Imageurls and want to slide it one by one when user slides image second image should dsplay,I have tried as belo but I only able to change when i touch,It changes on touch,But i want it on slide..So Please tell me what code changes should i make..Thank you
package com.epe.smaniquines.ui;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Timer;
import twitter4j.Twitter;
import twitter4j.auth.RequestToken;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.graphics.PointF;
import android.graphics.drawable.BitmapDrawable;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.provider.MediaStore.Images;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.URLSpan;
import android.util.Base64;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterViewFlipper;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewFlipper;
import com.epe.smaniquines.R;
import com.epe.smaniquines.adapter.FlipperAdapter;
import com.epe.smaniquines.adapter.ImageSwipeAdapter;
import com.epe.smaniquines.adapter.SimpleGestureFilter;
import com.epe.smaniquines.backend.AlertDialogManager;
import com.epe.smaniquines.backend.ConnectionDetector;
import com.epe.smaniquines.uc.Menu;
import com.epe.smaniquines.util.Const;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
public class DetailsActivity extends Activity implements OnClickListener,
OnTouchListener {
private SimpleGestureFilter detector;
ImageView proImage, ivSave, ivInfo, ivPlay, ivBak, iv_share;
RelativeLayout rl_botm, rl_option;
TextView tv_facebuk, tv_twiter, tv_nothanks, tv_email, tv_save, tv_quote;
String big_img;
int pos;
ViewPager viewPager;
ImageSwipeAdapter adapter;
private static SharedPreferences mSharedPreferences;
ArrayList<String> resultArray;
private DisplayImageOptions options;
public static ImageLoader imageLoader;
RelativeLayout rl_info;
public boolean flag = false;
Menu menu;
public boolean flag1 = false;
boolean isOnClick = false;
int i = 0;
String cat_nem;
File casted_image;
private int PicPosition;
private Handler handler = new Handler();
ProgressDialog pDialog;
ConnectionDetector cd;
// Alert Dialog Manager
AlertDialogManager alert = new AlertDialogManager();
int mFlipping = 0;
ViewFlipper viewFlipper;
Timer timer;
int flagD = 0;
String data;
String shareType;
File image;
static String PREFERENCE_NAME = "twitter_oauth";
static final String PREF_KEY_OAUTH_TOKEN = "oauth_token";
static final String PREF_KEY_OAUTH_SECRET = "oauth_token_secret";
static final String PREF_KEY_TWITTER_LOGIN = "isTwitterLogedIn";
TextView titledetail;
static final String TWITTER_CALLBACK_URL = "oauth://t4jsample";
// Twitter oauth urls
static final String URL_TWITTER_AUTH = "auth_url";
static final String URL_TWITTER_OAUTH_VERIFIER = "oauth_verifier";
static final String URL_TWITTER_OAUTH_TOKEN = "oauth_token";
public static String PACKAGE_NAME;
static String TWITTER_CONSUMER_KEY = "AzFSBq1Od4lYGGcGR0u9GkMIT"; // place
static String TWITTER_CONSUMER_SECRET = "MBwdard2Y4l6LT6z219NJ6x8aZ4jyK8JBKZ85usRPcDP8ujwM0"; // place
Matrix matrix = new Matrix();
Matrix savedMatrix = new Matrix();
static final int NONE = 0;
static final int DRAG = 1;
static final int ZOOM = 2;
int mode = NONE;
// Remember some things for zooming
PointF start = new PointF();
PointF mid = new PointF();
float oldDist = 1f;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_detail);
PACKAGE_NAME = getApplicationContext().getPackageName();
initialize();
cat_nem = getIntent().getStringExtra("cat_name");
System.out.println(":::::::::::CAt nem:::::::::" + cat_nem);
titledetail.setText(cat_nem);
proImage.setScaleType(ImageView.ScaleType.FIT_CENTER);
proImage.setOnTouchListener(this);
showHashKey(this);
printKeyHashForThisDevice();
pos = getIntent().getIntExtra("pos", 0);
cd = new ConnectionDetector(getApplicationContext());
// Check if Internet present
if (!cd.isConnectingToInternet()) {
// Internet Connection is not present
alert.showAlertDialog(DetailsActivity.this,
"Internet Connection Error",
"Please connect to working Internet connection", false);
// stop executing code by return
return;
}
// Check if twitter keys are set
if (TWITTER_CONSUMER_KEY.trim().length() == 0
|| TWITTER_CONSUMER_SECRET.trim().length() == 0) {
// Internet Connection is not present
alert.showAlertDialog(DetailsActivity.this, "Twitter oAuth tokens",
"Please set your twitter oauth tokens first!", false);
// stop executing code by return
return;
}
mSharedPreferences = getApplicationContext().getSharedPreferences(
"MyPref", 0);
/*
* Intent i = getIntent(); data = i.getStringExtra("data"); shareType =
* i.getStringExtra("type");
*/
big_img = getIntent().getStringExtra(Const.TAG_BIG_IMG);
// imageLoader.displayImage(big_img, proImage, options);
resultArray = getIntent().getStringArrayListExtra("array");
viewPager = (ViewPager) findViewById(R.id.view_pager);
viewPager.setVisibility(View.VISIBLE);
ImagePagerAdapter adapter = new ImagePagerAdapter();
viewPager.setCurrentItem(resultArray.indexOf(pos));
viewPager.setAdapter(adapter);
ivInfo.setOnClickListener(this);
ivPlay.setOnClickListener(this);
tv_email.setOnClickListener(this);
tv_facebuk.setOnClickListener(this);
tv_nothanks.setOnClickListener(this);
tv_save.setOnClickListener(this);
tv_twiter.setOnClickListener(this);
iv_share.setOnClickListener(this);
ivBak.setOnClickListener(this);
tv_quote.setOnClickListener(this);
proImage.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
viewPager.setVisibility(View.VISIBLE);
}
});
// viewFlipper = (ViewFlipper) findViewById(R.id.flipper);
/*
* imageLoader.displayImage(big_img, proImage, options);
* proImage.postDelayed(swapImage, 1000);
*/
viewPager.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_UP) {
if (isOnClick) {
if (event.getX() > viewPager.getWidth() / 2) {
// go to next
i = pos;
viewPager.setCurrentItem(resultArray.indexOf(i),
true);
i++;
} else {
viewPager.setCurrentItem(resultArray.indexOf(i),
true);
i--;
// go to previous
}
return true;
}
}
return false;
}
});
}
public void open(View view) {
Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
shareIntent.setType("*/*");
shareIntent.putExtra(Intent.EXTRA_TEXT, "Hello test"); // <- String
Uri screenshotUri = Uri.parse(image.getPath());
shareIntent.putExtra(Intent.EXTRA_STREAM, screenshotUri);
startActivity(Intent.createChooser(shareIntent, "Share image using"));
}
void initialize() {
proImage = (ImageView) findViewById(R.id.iv_det);
ivInfo = (ImageView) findViewById(R.id.iv_info);
ivPlay = (ImageView) findViewById(R.id.iv_play);
ivBak = (ImageView) findViewById(R.id.iv_back);
rl_botm = (RelativeLayout) findViewById(R.id.rl_bottom);
rl_option = (RelativeLayout) findViewById(R.id.rl_options);
tv_save = (TextView) findViewById(R.id.tv_save);
tv_email = (TextView) findViewById(R.id.tv_email);
tv_facebuk = (TextView) findViewById(R.id.tv_facebook);
tv_nothanks = (TextView) findViewById(R.id.tv_no_thanks);
tv_twiter = (TextView) findViewById(R.id.tv_twiter);
rl_option.setVisibility(View.GONE);
tv_quote = (TextView) findViewById(R.id.tv_qote);
iv_share = (ImageView) findViewById(R.id.iv_share);
imageLoader = ImageLoader.getInstance();
imageLoader.init(ImageLoaderConfiguration
.createDefault(DetailsActivity.this));
rl_info = (RelativeLayout) findViewById(R.id.rl_info);
rl_info.setVisibility(View.GONE);
resultArray = new ArrayList<String>();
ivPlay.setVisibility(View.VISIBLE);
titledetail = (TextView) findViewById(R.id.titledetail);
// twitter
// Login button
}
#SuppressLint("NewApi")
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.iv_share:
rl_option.setVisibility(View.VISIBLE);
rl_info.setVisibility(View.GONE);
if (flag1) {
rl_option.setVisibility(View.VISIBLE);
flag1 = false;
} else {
rl_option.setVisibility(View.GONE);
flag1 = true;
}
break;
case R.id.iv_play:
proImage.setVisibility(View.GONE);
AdapterViewFlipper flipper = (AdapterViewFlipper) findViewById(R.id.flipper);
flipper.setAutoStart(true);
flipper.setAdapter(new FlipperAdapter(DetailsActivity.this,
resultArray));
Animation in = AnimationUtils.loadAnimation(this,
android.R.anim.slide_in_left);
Animation out = AnimationUtils.loadAnimation(this,
android.R.anim.slide_out_right);
flipper.setAnimation(out);
ivPlay.setVisibility(View.INVISIBLE);
break;
case R.id.iv_back:
finish();
break;
case R.id.tv_email:
rl_option.setVisibility(View.GONE);
Intent email = new Intent(Intent.ACTION_SEND);
email.putExtra(Intent.EXTRA_EMAIL,
new String[] { "youremail#yahoo.com" });
email.putExtra(Intent.EXTRA_SUBJECT, "subject");
email.putExtra(Intent.EXTRA_TEXT, "message");
email.setType("message/rfc822");
startActivity(Intent.createChooser(email,
"Choose an Email client :"));
break;
case R.id.tv_save:
save();
rl_option.setVisibility(View.GONE);
break;
case R.id.tv_facebook:
// facebookShare();
/*
* save(); open(v);
*/
rl_option.setVisibility(View.GONE);
break;
case R.id.tv_no_thanks:
rl_option.setVisibility(View.GONE);
break;
case R.id.tv_twiter:
rl_option.setVisibility(View.GONE);
// loginToTwitter();
// new updateTwitterStatus().execute("3sManiquines");
break;
case R.id.iv_info:
rl_info.setVisibility(View.VISIBLE);
rl_option.setVisibility(View.GONE);
if (flag) {
rl_info.setVisibility(View.VISIBLE);
flag = false;
} else {
rl_info.setVisibility(View.GONE);
flag = true;
}
break;
case R.id.tv_qote:
rl_option.setVisibility(View.GONE);
String url = big_img;
SpannableStringBuilder builder = new SpannableStringBuilder();
builder.append("Hi Go to product for details:");
int start = builder.length();
builder.append(url);
int end = builder.length();
builder.setSpan(new URLSpan(url), start, end,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("message/rfc822");
i.putExtra(Intent.EXTRA_EMAIL, new String[] { "" });
i.putExtra(Intent.EXTRA_SUBJECT, "Quote");
i.putExtra(Intent.EXTRA_TEXT, builder);
startActivity(Intent.createChooser(i, "Select application"));
break;
}
}
public static void showHashKey(Context context) {
try {
PackageInfo info = context.getPackageManager().getPackageInfo(
"com.epe.3SManiquines", PackageManager.GET_SIGNATURES); // Your
// package
// name
// here
for (android.content.pm.Signature signature : info.signatures) {
MessageDigest md = MessageDigest.getInstance("SHA");
md.update(signature.toByteArray());
Log.v("KeyHash:",
Base64.encodeToString(md.digest(), Base64.DEFAULT));
}
} catch (NameNotFoundException e) {
} catch (NoSuchAlgorithmException e) {
}
}
// slide show..!!!
MediaPlayer introSound, bellSound;
Runnable swapImage = new Runnable() {
#Override
public void run() {
myslideshow();
handler.postDelayed(this, 1000);
}
};
private void myslideshow() {
PicPosition = resultArray.indexOf(big_img);
if (PicPosition >= resultArray.size())
PicPosition = resultArray.indexOf(big_img); // stop
else
resultArray.get(PicPosition);// move to the next gallery element.
}
//
// SAVE TO SD CARD..!!
void save() {
BitmapDrawable drawable = (BitmapDrawable) proImage.getDrawable();
Bitmap bitmap = drawable.getBitmap();
File sdCardDirectory = Environment.getExternalStorageDirectory();
File dir = new File(sdCardDirectory.getAbsolutePath()
+ "/3sManiquines/");
image = new File(sdCardDirectory, "3s_" + System.currentTimeMillis()
+ ".png");
dir.mkdirs();
boolean success = false;
// Encode the file as a PNG image.
FileOutputStream outStream;
try {
outStream = new FileOutputStream(image);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, outStream);
/* 100 to keep full quality of the image */
outStream.flush();
outStream.close();
success = true;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if (success) {
addImageToGallery(dir + "", DetailsActivity.this);
Toast.makeText(getApplicationContext(), "Image saved with success",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(),
"Error during image saving", Toast.LENGTH_LONG).show();
}
}//
public static void addImageToGallery(final String filePath,
final Context context) {
ContentValues values = new ContentValues();
values.put(Images.Media.DATE_TAKEN, System.currentTimeMillis());
values.put(Images.Media.MIME_TYPE, "image/png");
values.put(MediaStore.MediaColumns.DATA, filePath);
context.getContentResolver().insert(Images.Media.EXTERNAL_CONTENT_URI,
values);
}
// facebook...
private void printKeyHashForThisDevice() {
try {
System.out
.println("::::::::::::::::::::HAsh key called:::::::::::::");
PackageInfo info = getPackageManager().getPackageInfo(PACKAGE_NAME,
PackageManager.GET_SIGNATURES);
for (android.content.pm.Signature signature : info.signatures) {
MessageDigest md = MessageDigest.getInstance("SHA");
md.update(signature.toByteArray());
String keyHash = Base64.encodeToString(md.digest(),
Base64.DEFAULT);
System.out
.println(":::::::::::KEy hash:::::::::::::" + keyHash);
System.out.println("================KeyHash================ "
+ keyHash);
}
} catch (NameNotFoundException e) {
} catch (NoSuchAlgorithmException e) {
}
}
#Override
public boolean onTouch(View v, MotionEvent event) {
float touchPointX = event.getX();
float touchPointY = event.getY();
int[] coordinates = new int[2];
rl_info.getLocationOnScreen(coordinates);
rl_option.getLocationOnScreen(coordinates);
if (touchPointX < coordinates[0]
|| touchPointX > coordinates[0] + rl_info.getWidth()
|| touchPointY < coordinates[1]
|| touchPointY > coordinates[1] + rl_info.getHeight())
rl_info.setVisibility(View.INVISIBLE);
rl_option.setVisibility(View.INVISIBLE);
switch (event.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN: // first finger down only
break;
case MotionEvent.ACTION_UP: // first finger lifted
/*
* if (i < resultArray.size()) {
* imageLoader.displayImage(resultArray.get(i), proImage); i++; }
*/
case MotionEvent.ACTION_POINTER_UP: // second finger lifted
break;
case MotionEvent.ACTION_POINTER_DOWN: // second finger down
break;
case MotionEvent.ACTION_MOVE:
break;
}
return true;
}
//
private class ImagePagerAdapter extends PagerAdapter {
#Override
public int getCount() {
return resultArray.size();
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((ImageView) object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
Context context = DetailsActivity.this;
ImageView imageView = new ImageView(context);
int padding = context.getResources().getDimensionPixelSize(
R.dimen.padding_medium);
imageView.setPadding(padding, padding, padding, padding);
imageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
imageLoader.displayImage(resultArray.get(position), proImage);
((ViewPager) container).addView(imageView, 0);
return imageView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
((ViewPager) container).removeView((ImageView) object);
}
}
}
If you don't want the way ViewPager slide and handles pages , then you have to implement you own view ( Not with ViewPager ).
ViewPager by default slides through the pages on swipe.
If you want to slide on clicking left or right side to the viewpager , then on touch ACTION_UP call
viewPager.setCurrentItem( PAGE_NUM , true );
This will slide to next or previous page and load appropriate image url.
You can use ViewPager with fragments for each image url.
This way the memory used to draw image will be handled well by viewpager...
More the image reference you keep in memory , more the possibility of the app crashing.
May I know why the weather didn't display after I type in the location?
After I press enter, it gave me force close error.
I'm getting the weather information from google weather API.
Below are my codes.
MainActivity.java
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
class ForecastInformation{
String city;
String postal_code;
String forecast_date;
String current_date_time;
String unit_system;
}
class CurrentConditions{
String condition;
String temp_f;
String temp_c;
String humidity;
String icon;
String wind_condition;
}
class ForecastConditions{
String day_of_week;
String low;
String high;
String icon;
String condition;
}
ForecastInformation forecastInformation;
CurrentConditions currentConditions;
List<ForecastConditions> forecastConditionsList;
Button buttonEnter;
EditText edittextPlace;
ImageView iconCurrent;
TextView textCurrent;
TextView textInfo;
ListView listForcast;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonEnter = (Button)findViewById(R.id.enter);
edittextPlace = (EditText)findViewById(R.id.place);
iconCurrent = (ImageView)findViewById(R.id.iconcurrent);
textCurrent = (TextView)findViewById(R.id.textcurrent);
textInfo = (TextView)findViewById(R.id.textinfo);
listForcast = (ListView)findViewById(R.id.listforcast);
buttonEnter.setOnClickListener(EnterOnClickListener);
}
Button.OnClickListener EnterOnClickListener
= new Button.OnClickListener(){
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
String place = edittextPlace.getText().toString();
String weatherString = QueryGoogleWeather(place);
Document weatherDoc = convertStringToDocument(weatherString);
if(parseGoogleWeather(weatherDoc)){
//Display Result
String c = currentConditions.condition + "\n"
+ currentConditions.temp_f + "f\n"
+ currentConditions.temp_c + "c\n"
+ currentConditions.humidity + "\n"
+ currentConditions.wind_condition + "\n";
textCurrent.setText(c);
Bitmap bm = LoadIcon(currentConditions.icon);
iconCurrent.setImageBitmap(bm);
textInfo.setText("city: " + forecastInformation.city + "\n"
+ "postal code: " + forecastInformation.postal_code + "\n"
+ "forecast date: " + forecastInformation.forecast_date + "\n"
+ "current date time: " + forecastInformation.current_date_time + "\n"
+ "unit: " + forecastInformation.unit_system);
listForcast.setAdapter(new MyCustomAdapter(
MainActivity.this,
R.layout.row,
forecastConditionsList));
}
}
};
public class MyCustomAdapter extends ArrayAdapter<ForecastConditions> {
public MyCustomAdapter(Context context, int textViewResourceId,
List<ForecastConditions> objects) {
super(context, textViewResourceId, objects);
// TODO Auto-generated constructor stub
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater=getLayoutInflater();
View row=inflater.inflate(R.layout.row, parent, false);
ImageView iconForecast = (ImageView)row.findViewById(R.id.iforecast);
TextView textForecast = (TextView)row.findViewById(R.id.tforecast);
textForecast.setText(
forecastConditionsList.get(position).day_of_week + "\n"
+ " - " + forecastConditionsList.get(position).condition + "\n"
+ forecastConditionsList.get(position).low + " ~ "
+ forecastConditionsList.get(position).high);
Bitmap bm = LoadIcon(forecastConditionsList.get(position).icon);
iconForecast.setImageBitmap(bm);
return row;
}
}
private Bitmap LoadIcon(String iconURL)
{
BitmapFactory.Options bmOptions;
bmOptions = new BitmapFactory.Options();
bmOptions.inSampleSize = 1;
String image_URL = "http://www.google.com" + iconURL;
Bitmap bitmap = null;
InputStream in = null;
try {
in = OpenHttpConnection(image_URL);
bitmap = BitmapFactory.decodeStream(in, null, bmOptions);
in.close();
} catch (IOException e1) {
}
return bitmap;
}
private InputStream OpenHttpConnection(String strURL) throws IOException{
InputStream inputStream = null;
URL url = new URL(strURL);
URLConnection conn = url.openConnection();
try{
HttpURLConnection httpConn = (HttpURLConnection)conn;
httpConn.setRequestMethod("GET");
httpConn.connect();
if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
inputStream = httpConn.getInputStream();
}
}catch (Exception ex){
}
return inputStream;
}
private boolean parseGoogleWeather(Document srcDoc){
boolean result = false;
forecastInformation = new ForecastInformation();
currentConditions = new CurrentConditions();
//-- Get forecast_information
NodeList forecast_information = srcDoc.getElementsByTagName("forecast_information");
if (forecast_information.getLength() > 0){
//Assume place found if "forecast_information" exist
result = true;
NodeList infoChilds = forecast_information.item(0).getChildNodes();
for(int i=0; i<infoChilds.getLength(); i++){
Node n = infoChilds.item(i);
String nName = n.getNodeName();
String nValue
= n.getAttributes().getNamedItem("data").getNodeValue().toString();
if (nName.equalsIgnoreCase("city")){
forecastInformation.city = nValue;
}else if((nName.equalsIgnoreCase("postal_code"))){
forecastInformation.postal_code = nValue;
}else if((nName.equalsIgnoreCase("forecast_date"))){
forecastInformation.forecast_date = nValue;
}else if((nName.equalsIgnoreCase("current_date_time"))){
forecastInformation.current_date_time = nValue;
}else if((nName.equalsIgnoreCase("unit_system"))){
forecastInformation.unit_system = nValue;
}
}
}
//-- Get current_conditions
NodeList current_conditions = srcDoc.getElementsByTagName("current_conditions");
if(current_conditions.getLength()>0){
NodeList currentChilds = current_conditions.item(0).getChildNodes();
for(int i=0; i<currentChilds.getLength(); i++){
Node n = currentChilds.item(i);
String nName = n.getNodeName();
String nValue
= n.getAttributes().getNamedItem("data").getNodeValue().toString();
if (nName.equalsIgnoreCase("condition")){
currentConditions.condition = nValue;
}else if((nName.equalsIgnoreCase("temp_f"))){
currentConditions.temp_f = nValue;
}else if((nName.equalsIgnoreCase("temp_c"))){
currentConditions.temp_c = nValue;
}else if((nName.equalsIgnoreCase("humidity"))){
currentConditions.humidity = nValue;
}else if((nName.equalsIgnoreCase("icon"))){
currentConditions.icon = nValue;
}else if((nName.equalsIgnoreCase("wind_condition"))){
currentConditions.wind_condition = nValue;
}
}
}
//-- Get forecast_conditions
NodeList forecast_conditions = srcDoc.getElementsByTagName("forecast_conditions");
if (forecast_conditions.getLength()>0){
int forecast_conditions_length = forecast_conditions.getLength();
forecastConditionsList = new ArrayList<ForecastConditions>();
for(int j=0; j<forecast_conditions_length; j++){
ForecastConditions tmpForecastConditions = new ForecastConditions();
NodeList forecasrChilds = forecast_conditions.item(j).getChildNodes();
for(int i=0; i<forecasrChilds.getLength(); i++){
Node n = forecasrChilds.item(i);
String nName = n.getNodeName();
String nValue
= n.getAttributes().getNamedItem("data").getNodeValue().toString();
if (nName.equalsIgnoreCase("condition")){
tmpForecastConditions.condition = nValue;
}else if((nName.equalsIgnoreCase("day_of_week"))){
tmpForecastConditions.day_of_week = nValue;
}else if((nName.equalsIgnoreCase("low"))){
tmpForecastConditions.low = nValue;
}else if((nName.equalsIgnoreCase("high"))){
tmpForecastConditions.high = nValue;
}else if((nName.equalsIgnoreCase("icon"))){
tmpForecastConditions.icon = nValue;
}
}
forecastConditionsList.add(tmpForecastConditions);
}
}
return result;
}
private Document convertStringToDocument(String src){
Document dest = null;
DocumentBuilderFactory dbFactory =
DocumentBuilderFactory.newInstance();
DocumentBuilder parser;
try {
parser = dbFactory.newDocumentBuilder();
dest = parser.parse(new ByteArrayInputStream(src.getBytes()));
} catch (ParserConfigurationException e1) {
e1.printStackTrace();
Toast.makeText(MainActivity.this,
e1.toString(), Toast.LENGTH_LONG).show();
} catch (SAXException e) {
e.printStackTrace();
Toast.makeText(MainActivity.this,
e.toString(), Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(MainActivity.this,
e.toString(), Toast.LENGTH_LONG).show();
}
return dest;
}
private String QueryGoogleWeather(String p){
String uriPlace = Uri.encode(p);
String qResult = "";
String queryString = "http://www.google.com/ig/api?hl=en&weather=" + uriPlace;
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(queryString);
try {
HttpEntity httpEntity = httpClient.execute(httpGet).getEntity();
if (httpEntity != null){
InputStream inputStream = httpEntity.getContent();
Reader in = new InputStreamReader(inputStream);
BufferedReader bufferedreader = new BufferedReader(in);
StringBuilder stringBuilder = new StringBuilder();
String stringReadLine = null;
while ((stringReadLine = bufferedreader.readLine()) != null) {
stringBuilder.append(stringReadLine + "\n");
}
qResult = stringBuilder.toString();
}
} catch (ClientProtocolException e) {
e.printStackTrace();
Toast.makeText(MainActivity.this,
e.toString(), Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(MainActivity.this,
e.toString(), Toast.LENGTH_LONG).show();
}
return qResult;
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="hello" />
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="#+id/enter"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="- Enter -"/>
<EditText
android:id="#+id/place"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="center">
<ImageView
android:id="#+id/iconcurrent"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp"/>
<TextView
android:id="#+id/textcurrent"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textStyle="bold"
android:gravity="center"/>
</LinearLayout>
<TextView
android:id="#+id/textinfo"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
<ListView
android:id="#+id/listforcast"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
</ListView>
</LinearLayout>
row.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<ImageView
android:id="#+id/iforecast"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp" />
<TextView
android:id="#+id/tforecast"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
The google weather API has been deprecated. Google discontinued it. This is why your query returns no result.
I got my app to read an app and then tell me what the code says, but now I'm trying to have it encode the string back into a barcode and display it as an image on the screen. However, it always force closes the app before it starts. Here is my code, please help:
import java.util.EnumMap;
import java.util.Map;
import android.os.Bundle;
import android.app.ActionBar.LayoutParams;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.drawable.BitmapDrawable;
import android.view.Gravity;
import android.view.Menu;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
public class Main extends Activity {
IntentIntegrator integrator = new IntentIntegrator(this);
private static final int WHITE = 0xFFFFFFFF;
private static final int BLACK = 0xFF000000;
LinearLayout myLayout = (LinearLayout)findViewById(R.id.myLayout);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//LinearLayout myLayout = (LinearLayout)findViewById(R.id.myLayout);
Button btn =(Button)findViewById(R.id.button1);
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
integrator.initiateScan();
}
});
}
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
IntentResult scanResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
if (scanResult != null) {
Toast.makeText(Main.this,
"works",
Toast.LENGTH_SHORT).show();
String contents = intent.getStringExtra("SCAN_RESULT");
String format = intent.getStringExtra("SCAN_RESULT_FORMAT");
Toast.makeText(Main.this,
contents,
Toast.LENGTH_SHORT).show();
Bitmap bitmap = null;
ImageView iv = new ImageView(this);
try {
bitmap = encodeAsBitmap(contents, BarcodeFormat.CODE_128, 600, 300);
iv.setImageBitmap(bitmap);
} catch (WriterException e) {
e.printStackTrace();
}
myLayout.addView(iv);
TextView tv = new TextView(this);
tv.setGravity(Gravity.CENTER_HORIZONTAL);
tv.setText(contents);
myLayout.addView(tv);
}
}
Bitmap encodeAsBitmap(String contents, BarcodeFormat format, int img_width, int img_height) throws WriterException {
String contentsToEncode = contents;
if (contentsToEncode == null) {
return null;
}
Map<EncodeHintType, Object> hints = null;
hints = new EnumMap<EncodeHintType, Object>(EncodeHintType.class);
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
MultiFormatWriter writer = new MultiFormatWriter();
BitMatrix result;
try {
result = writer.encode(contentsToEncode, format, img_width, img_height, hints);
} catch (IllegalArgumentException iae) {
// Unsupported format
return null;
}
int width = result.getWidth();
int height = result.getHeight();
int[] pixels = new int[width * height];
for (int y = 0; y < height; y++) {
int offset = y * width;
for (int x = 0; x < width; x++) {
pixels[offset + x] = result.get(x, y) ? BLACK : WHITE;
}
}
Bitmap bitmap = Bitmap.createBitmap(width, height,
Bitmap.Config.ARGB_8888);
bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
return bitmap;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
IntentResult and IntentIntegrator are both from ZXing.
Log Cat:
03-15 13:05:04.303: E/AndroidRuntime(4363): FATAL EXCEPTION: main
In your toast, instead of Main.this you should try getApplicationContext(). Also recall that an Activity is a type of Context.
Try to move this:
LinearLayout myLayout = (LinearLayout)findViewById(R.id.myLayout);
under:
setContentView(R.layout.main);
I am developing an application on Android 2.2 . Mainly what it does , is that it grab data from the internet and then it shows it on the device's screen. I have finished an Activity , but , it is too slow , it takes too much to get the web content . I would like to make it run faster . I guess that Async Task would be the most appropriate method that I should use . I've tried to change the code , to insert the Async Task but I cant figure out how to do it right .
This is my code :
package com.nextlogic.golfnews;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Html;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageView;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
public class Activity1 extends Activity {
View vw;
ImageView im;
Bitmap bmp;
URL url = null;
//ImageView t;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main2);
String s="";
String pag="";
String aux1="";
ArrayList<String> pg;
ArrayList<String> links;
ArrayList<String> sbt;
TableLayout tableView = (TableLayout) findViewById(R.id.tableView);
String q="";
String tt="";
pag=getPage();
aux1=pag.substring(pag.indexOf("\">Annonse<"),pag.indexOf("<!-- START articleListBullets -->"));
pg=title(aux1);
links=urls(aux1);
sbt=subtitle(aux1);
///////////////////////////////////////////////////////////////////////////
for(int i=0; i<pg.size(); i++) {
s = "http://www.golfnews.no/" +links.get(i);
q=pg.get(i);
tt=sbt.get(i);
// create a new TableRow
TableRow row = new TableRow(this);
row.setBackgroundColor(Color.WHITE);
row.setTag(i);
row.setClickable(true);
row.setClickable(true);
row.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent myIntent = new Intent(view.getContext(), News.class);
startActivityForResult(myIntent, 0);
}
});
// create a new TextView
TextView fin = new TextView(this);
vw = new View(this);
im = new ImageView(this);
////////////////////////////////////
bmp=getbmp(s);
im.setImageBitmap(bmp);
vw.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.FILL_PARENT, 1));
vw.setBackgroundColor(Color.LTGRAY);
row.addView(im, new TableRow.LayoutParams(70,30));
q=titleEdit(q);
tt=subtitleEdit(tt);
//////////////////////////////////////
fin.setText(Html.fromHtml("<b>" + q + "</b>" + "<br />" +
"<small>" + tt + "</small>"));
row.addView(fin);
tableView.addView(vw);
tableView.addView(row, new TableLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
}
}
public Bitmap getbmp(String s)
{
Bitmap bmp = null;
try{
url = new URL(s);
}
catch(MalformedURLException e)
{
e.printStackTrace();
}
try{
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setDoInput(true);
conn.connect();
InputStream is = conn.getInputStream();
bmp = BitmapFactory.decodeStream(is);
} catch (IOException e)
{
e.printStackTrace();
}
return bmp;
}
public String titleEdit(String q)
{
if(q.length()>33)
{
String q1 = q.substring(0,33);
String q2 = q.substring(33);
q =q1 + "<br />" +q2;
}
return q;
}
public String subtitleEdit(String tt)
{
if(tt.length()>40)
{
String tt1 = tt.substring(0,40);
String tt2 = tt.substring(40);
if(tt2.length()>42)
{
String z1 = tt2.substring(0,40);
String z2 = tt2.substring(40);
if(z2.length()>42)
{
String z21 = z2.substring(0,40);
String z22 = z2.substring(40);
z2=z21+"<br />"+z22;
}
tt2=z1+"<br />"+z2;
}
tt = "<br />"+tt1 + "<br />" +tt2;
}
return tt;
}
private ArrayList<String> title (String trax)
{
ArrayList<String> result= new ArrayList<String>();
int ok=1;
int s1,s2;
while(ok==1)
{
//System.out.println("INDEX = "+trax.indexOf("alt="));
ok=0;
if((trax.indexOf("alt=")!=-1&&trax.indexOf("\"/>")!=-1)&&((trax.indexOf("alt=")<trax.indexOf("\"/>"))))
{
ok=1;
s1 =trax.indexOf("alt=");
s2 = trax.indexOf("\"/>");
//System.out.println("s1= "+s1+" s2 = "+s2+" length="+trax.length());
result.add(trax.substring(s1+5,s2));
// i++;
trax = trax.substring(s2 + 3);
}
}
return result;
}
private ArrayList<String> subtitle (String trax)
{
ArrayList<String> result= new ArrayList<String>();
int ok=1;
int s1,s2;
while(ok==1)
{
ok=0;
if(trax.indexOf("<p>")!=-1)
{
ok=1;
s1 =trax.indexOf("<p>");
s2 = trax.indexOf(")");
//System.out.println("s1= "+s1+" s2 = "+s2+" length="+trax.length());
result.add(trax.substring(s1+3,s2+1));
trax = trax.substring(s2+1 );
}
}
return result;
}
private ArrayList<String> urls (String trax)
{
ArrayList<String> result= new ArrayList<String>();
int ok=1;
int s1,s2;
while(ok==1)
{
//System.out.println("INDEX = "+trax.indexOf("alt="));
ok=0;
if((trax.indexOf("<img src")!=-1&&trax.indexOf("alt=\"")!=-1)&&((trax.indexOf("<img src")<trax.indexOf("alt=\""))))
{
ok=1;
s1 =trax.indexOf("<img src");
s2 = trax.indexOf("alt=\"");
// System.out.println("s1= "+s1+" s2 = "+s2+" length="+trax.length());
result.add(trax.substring(s1+10,s2-2));
// i++;
trax = trax.substring(s2 + 6);
}
}
return result;
}
private String getPage() {
String str = "***";
try
{
HttpClient hc = new DefaultHttpClient();
HttpPost post = new HttpPost("http://golfnews.no/nyheter.php");
HttpResponse rp = hc.execute(post);
if(rp.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
{
str = EntityUtils.toString(rp.getEntity());
}
}catch(IOException e){
e.printStackTrace();
}
return str;
}
}
The Activity takes too much time to load .(About 10 seconds) . So please , can you help me figure out where and how to insert the Async Task ? Or maybe you can suggest me something else to make the application run faster ? Something like a handler for example ? I don't really know much since I am new to Android programming . Any advice would be much appreciated . Thanks.
1) You need improve your code style
2) For such purposes you must use AsynchTask or Handler+Separate Thread
1,2