please am working on a class project which i will submit soon and i need your help.am trying to get image saved in varbinary format in my sql server 2016 into my android Image view.i have been stock at this level for a while and i need help to cross it.i have also check google and youtube but the answers i found did not help me out.other values in my database table gets retrieved except the image when i look at the log file it tels me no adapter attached skipping layout.as you will see in the code my adapter is attached.help please help. below is my codes
for connecting to the database using jtds
package com.example.abun.shoprite1;
import java.lang.String;
import java.io.File;
import android.annotation.SuppressLint;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import static java.nio.file.Files.size;
import java.sql.*;
import java.util.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.os.StrictMode;
import android.util.Log;
public class ConnectionClass {
String url;
String serverName;
String instanceName;
String databaseName;
String userName;
String password;
String port;
String sql;
ConnectionClass() {
serverName = "192.168.80.1";
port ="1433";
//instanceName = "";
databaseName = "shoprite";
userName = "abun2";
password = "shoprite";
}
private String getConnectionUrl() {
// Constructing the connection string
return url + serverName +" ;DatabaseName = " +databaseName +";user="+userName + ";password="+password +";";
}
//private String getConnectionUrl() {
// Constructing the connection string
//return url + serverName +" ;DatabaseName = " +databaseName+"; integratedSecurity=true";
//}
#SuppressLint("NewApi")
public Connection getConnection() throws SQLException, ClassNotFoundException {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
String ConnUrl;
//String conny= "jdbc:jtds:sqlserver://"+ serverName+ ":" +port+ ";"+ " ;DatabaseName = " +databaseName+"; integratedSecurity=true";
ConnUrl="jdbc:jtds:sqlserver://" + serverName+ ":" +port+ ";"+ "databaseName=" + databaseName + ";user=" + userName + ";password=" + password + ";";
Connection con =null;
try {
Class.forName("net.sourceforge.jtds.jdbc.Driver").newInstance();
con = DriverManager.getConnection(ConnUrl);
//con = DriverManager.getConnection(conny);
//""+"jdbc:jtds:sqlserver://127.0.0.1/shoprite; integrated security=true"
// Establishing the connection
//con = DriverManager.getConnection(getConnectionUrl());
//con = DriverManager.getConnection(ConnUrl);
if(con != null){
System.out.println("Connection Successful!");
}
else{
System.out.println(" no Connection ");
}
}catch(SQLException se){
Log.e("ERROR--",se.getMessage());
Log.e("ERROR--",se.getSQLState());
Log.e("ERROR--",se.getLocalizedMessage());
Log.e("ERROR--",se.getCause().toString());
Log.e("ERROR--",se.getStackTrace().toString());
}catch(ClassNotFoundException se){
Log.e("ERROR--",se.getMessage());
Log.e("ERROR--",se.getLocalizedMessage());
}catch(Exception se){
Log.e("ERROR--",se.getMessage());
Log.e("ERROR--",se.getLocalizedMessage());
}
return con;
}
public boolean verifyCustomer(String username,String password)throws SQLException{
Connection con1;
ResultSet resultSet = null;
String query = "select * from Customer_Details where Customer_Name =? and Password=?";
try {
con1 = getConnection();
PreparedStatement stmt = con1.prepareStatement(query,ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
stmt.setString(1, username);
stmt.setString(2, password);
resultSet = stmt.executeQuery();
if(resultSet.next()){
return true;
}else{
return false;
}
}catch(Exception e){
return false;
} finally {
if(resultSet != null)
resultSet.close();
}
}
public boolean verifyEmployee(String username,String password)throws SQLException{
Connection con1;
ResultSet resultSet = null;
String query = "select * from Employee_Details where Employee_Name =? and Designation=?";
try {
con1 = getConnection();
PreparedStatement stmt = con1.prepareStatement(query,ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
stmt.setString(1, username);
stmt.setString(2, password);
resultSet = stmt.executeQuery();
if(resultSet.next()){
return true;
}else{
return false;
}
}catch(Exception e){
return false;
} finally {
if(resultSet != null)
resultSet.close();
}
}
public boolean insertDataCustomer(String name, String gender,String address,int phone,
String DOB,String password,String email,int creditcard,String creditCardType){
Connection con1;
String query = "insert into Customer_Details(Customer_Name,Gender,Address,Phone,DOB,Password,CreditCardNo,CreditCardType) values( ?, ?, ?, ?,?,?,?,?)";
try {
con1 = getConnection();
PreparedStatement stmt = con1.prepareStatement(query);
stmt.setString(1, name);
stmt.setString(2, gender);
stmt.setString(3, address);
stmt.setInt(4, phone);
stmt.setString(5, DOB);
stmt.setString(6, password);
//stmt.setString(7, email);
stmt.setInt(7, creditcard);
stmt.setString(8, creditCardType);
long ent= stmt.executeUpdate();
if(ent == -1)
return false;
else
return true;
}catch(Exception e){
// System.out.println(e.getMessage());
Log.e( "error here: ",e.getMessage());
Log.e( "error here: ",e.getLocalizedMessage());
Log.e( "error here: ",e.getCause().toString());
return false;
}
}
public boolean insertDataEmployee(String ID, String name, String gender,
String DOB,String Designation,String address,String email,String phone){
Connection con1;
String query = "insert into Employee_Details(ID,name,gender,DOB,Designation,address,email,phone) values(?, ?, ?, ?, ?,?,?,?)";
try {
con1 = getConnection();
PreparedStatement stmt = con1.prepareStatement(query);
stmt.setString(1, name);
stmt.setString(2, gender);
stmt.setString(3, DOB);
stmt.setString(4, Designation);
stmt.setString(5, address);
stmt.setString(6, email);
stmt.setString(7, phone);
long ent= stmt.executeUpdate();
if(ent == -1)
return false;
else
return true;
}catch(Exception e){
// System.out.println(e.getMessage());
Log.e( "error here: ",e.getMessage());
return false;
}
}
public void veiwOrders()throws SQLException{
Connection con1;
ResultSet resultSet = null;
String query = "select * from Order_Details";
try {
con1 = getConnection();
PreparedStatement stmt = con1.prepareStatement(query,ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
resultSet = stmt.executeQuery();
if(resultSet.next()){
while(resultSet.next()){
}
}
}catch(Exception e){
//return false;
} finally {
if(resultSet != null)
resultSet.close();
}
}
}
below is my activity class
package com.example.abun.shoprite1;
/**
* Created by Abun on 5/12/2018.
*/
import android.app.Activity;
import android.app.ProgressDialog;
import android.support.annotation.RequiresPermission.Write;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.MenuItem;
import android.os.AsyncTask;
import android.support.design.widget.NavigationView;
import android.content.Intent;
//import android.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.view.View;
import android.support.v7.app.ActionBar;
import android.widget.Toast;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
public class productPage extends AppCompatActivity {
private RecyclerView mRecycler;
private RecyclerView.LayoutManager mLayoutManager;
private RecyclerView.Adapter mAdapter;
private DrawerLayout mDrawerLayout;
private ArrayList<String> mData;
private ArrayList<ProductPageRetrive> data;
ConnectionClass db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.productpage1);
db = new ConnectionClass();
data = new ArrayList<ProductPageRetrive>();
mData = new ArrayList<>();
for (int i = 0;i<30;i++){
mData.add("new title"+i);
}
SyncData orderData = new SyncData();
orderData.execute("");
mRecycler = (RecyclerView) findViewById(R.id.recycler_view);
mRecycler.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(productPage.this,LinearLayoutManager.HORIZONTAL,false);
mRecycler.setLayoutManager(mLayoutManager);
mAdapter = new MainAdapter(data,productPage.this);
mRecycler.setAdapter(mAdapter);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar actionbar = getSupportActionBar();
actionbar.setDisplayHomeAsUpEnabled(true);
actionbar.setHomeAsUpIndicator(R.mipmap.ic_launcher);
mDrawerLayout = findViewById(R.id.drawer_layout);
mDrawerLayout.addDrawerListener(
new DrawerLayout.DrawerListener() {
#Override
public void onDrawerSlide(View drawerView, float slideOffset) {
// Respond when the drawer's position changes
}
#Override
public void onDrawerOpened(View drawerView) {
// Respond when the drawer is opened
}
#Override
public void onDrawerClosed(View drawerView) {
// Respond when the drawer is closed
}
#Override
public void onDrawerStateChanged(int newState) {
// Respond when the drawer motion state changes
}
}
);
NavigationView navigationView = findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(
new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
// set item as selected to persist highlight
menuItem.setChecked(true);
// close drawer when item is tapped
mDrawerLayout.closeDrawers();
// Add code here to update the UI based on the item selected
// For example, swap UI fragments here
return true;
}
});
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
mDrawerLayout.openDrawer(GravityCompat.START);
return true;
}
return super.onOptionsItemSelected(item);
}
private class SyncData extends AsyncTask<String ,String,String>{
String msg="Internet/DB_Credentials/Windows_FireWall_TurnOn Error, see android monitor in the buttom for details";
ProgressDialog progress;
boolean success = false;
#Override
protected void onPreExecute(){
progress = ProgressDialog.show(productPage.this,"Synchronising","RecyclerView loading! please wait...",true);
}
#Override
protected String doInBackground(String...strings){
try {
Connection con = db.getConnection();
ResultSet resultSet = null;
if (con == null) {
msg="No Data found";
success = false;
}else{
String query = "SELECT * FROM Product_Details";
PreparedStatement stmt = con.prepareStatement(query, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
resultSet = stmt.executeQuery();
while (resultSet.next()) {
try {
data.add(new ProductPageRetrive(resultSet.getBinaryStream("Image"), resultSet.getInt("Price"), resultSet.getInt("Discount")));
}catch(Exception ex){
ex.printStackTrace();
}
}
msg ="found";
success=true;
}
}catch(Exception e){
e.printStackTrace();
//Write write = new StringWriter();
//e.printStackTrace(new PrintWriter(write));
//msg=writer.toString();
success=false;
}
return msg;
}
#Override
protected void onPostExecute(String msg){
progress.dismiss();
Toast.makeText(productPage.this,msg+"",Toast.LENGTH_LONG).show();
if(success == true){
mAdapter.notifyDataSetChanged();
}else{
try{
}catch (Exception e){
}
}
}
}
}
below is the data object for the array data;
package com.example.abun.shoprite1;
import java.io.InputStream;
import java.sql.Blob;
import java.sql.ResultSet;
/**
* Created by Abun on 6/14/2018.
*/
public class ProductPageRetrive {
private int price;
private int rating;
private String img1;
private InputStream ism;
private ResultSet rs;
public ProductPageRetrive(InputStream is, int money, int rate){
this.ism=is;
this.price=money;
this.rating=rate;
}
public int getRating() {
return rating;
}
public void setRating(int rating) {
this.rating = rating;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public String getImg1() {
return img1;
}
public void setImg1(String img1) {
this.img1 = img1;
}
public InputStream getIsm() {
return ism;
}
public void setIsm(InputStream ism) {
this.ism = ism;
}
}
below is my adapter class
package com.example.abun.shoprite1;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.v7.widget.RecyclerView;
import android.util.Base64;
import java.io.FileOutputStream;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Blob;
import java.sql.SQLException;
import java.util.ArrayList;
import com.squareup.picasso.Picasso;
import android.content.Context;
/**
* Created by Abun on 6/13/2018.
*/
public class MainAdapter extends RecyclerView.Adapter<MainAdapter.ViewHolder> {
private ArrayList<String> mData;
private ArrayList<ProductPageRetrive> Data;
private Context ct1;
public MainAdapter(ArrayList<String> Data1){
this.mData=Data1;
}
public MainAdapter(ArrayList<ProductPageRetrive> Data, Context ct)
{
this.Data=Data;
this.ct1 =ct;
}
#Override
public MainAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.contain,parent,false);
// set the view size, margin,padding and layout parameters
ViewHolder vh = new ViewHolder(v);
return vh;
}
#Override
public void onBindViewHolder(MainAdapter.ViewHolder holder, int position) {
int py =Data.get(position).getRating();
String pp = py +"";
holder.mtitle.setText(pp);
try {
InputStream is = Data.get(position).getIsm();
OutputStream os = new FileOutputStream(new File("photo1.jpg"));
byte[] content = new byte[1024];
int size = 0;
while((size=is.read(content))!=-1){
os.write(content,0,size);
}
os.close();
is.close();
//Picasso.get().load("file:photo1.jpg").into(holder.img);
Picasso.get().load("file:photo1.jpg").into(holder.img);
}catch (Exception e){
}
/*byte[] decorde = Base64.decode(Data.get(position).getImg1(),Base64.DEFAULT);
Bitmap mp = BitmapFactory.decodeByteArray(decorde,0,decorde.length);
holder.img.setImageBitmap(mp);*/
}
#Override
public int getItemCount() {
return Data.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
public TextView mtitle;
public TextView mtitle1;
public ImageView img;
public View layout;
public ViewHolder(View itemView){
super(itemView);
layout = itemView;
mtitle = (TextView) itemView.findViewById(R.id.mtitle);
img = (ImageView) itemView.findViewById(R.id.imaging);
}
}
}
Related
When I try to send debug the app it gives
09-02 14:56:41.137 32737-32737/com.example.motasemx.itsproject
D/KANZEN_DEBUG:
{"amount":1,"id":0,"link":"https://s6.postimg.cc/y2upelugx/menu1.jpg","name":"California
Maki x1","price":99.0} 09-02 14:56:41.140
32737-32737/com.example.motasemx.itsproject D/DEBUG: null
Please tell me what I am doing wrong
Here's my FoodAdapter
package com.example.motasemx.itsproject.Adapter;
import android.app.AlertDialog;
import android.app.Application;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.telecom.Call;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.cepheuen.elegantnumberbutton.view.ElegantNumberButton;
import com.example.motasemx.itsproject.Database.BackgroundTask;
import com.example.motasemx.itsproject.Database.ModelDB.Cart;
import com.example.motasemx.itsproject.HomeActivity;
import com.example.motasemx.itsproject.Interface.ItemClickListener;
import com.example.motasemx.itsproject.MainActivity;
import com.example.motasemx.itsproject.Model.Food;
import com.example.motasemx.itsproject.Model.order;
import com.example.motasemx.itsproject.R;
import com.example.motasemx.itsproject.Retrofit.IKanzenAPI;
import com.example.motasemx.itsproject.Utils.Common;
import com.google.gson.Gson;
import com.squareup.picasso.Picasso;
import org.w3c.dom.Text;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import dmax.dialog.SpotsDialog;
import retrofit2.Callback;
import retrofit2.Response;
public class FoodAdapter extends RecyclerView.Adapter<FoodViewHolder> {
Context context;
List<Food> foodList;
IKanzenAPI mService;
RequestQueue requestQueue;
public FoodAdapter(Context context, List<Food> foodList) {
this.context = context;
this.foodList = foodList;
}
#NonNull
#Override
public FoodViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(context).inflate(R.layout.food_item_layout,null);
return new FoodViewHolder(itemView);
}
#Override
public void onBindViewHolder(#NonNull FoodViewHolder holder, final int position) {
holder.txt_price.setText(new StringBuilder("₱").append(foodList.get(position).Price).toString());
holder.txt_food_name.setText(foodList.get(position).Name);
Picasso.with(context)
.load(foodList.get(position).Link)
.into(holder.img_product);
holder.setItemClickListener(new ItemClickListener() {
#Override
public void onCLick(View v) {
Toast.makeText(context, "Clicked!", Toast.LENGTH_SHORT).show();
}
});
holder.btn_add_to_cart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showAddToCartDialog(position);
}
});
}
private void showAddToCartDialog(final int position) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
View itemView = LayoutInflater.from(context)
.inflate(R.layout.add_to_cart_layout,null);
ImageView img_product_dialog = (ImageView)itemView.findViewById(R.id.img_cart_product);
final ElegantNumberButton txt_count = (ElegantNumberButton)itemView.findViewById(R.id.txt_count);
TextView txt_product_name = (TextView)itemView.findViewById(R.id.txt_cart_product_name);
TextView txt_descript = (TextView)itemView.findViewById(R.id.txt_descript);
Picasso.with(context)
.load(foodList.get(position).Link)
.into(img_product_dialog);
txt_product_name.setText(foodList.get(position).Name);
txt_descript.setText(foodList.get(position).Description);
builder.setView(itemView);
builder.setNegativeButton("ADD TO CART", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
showConfirmDialog(position,txt_count.getNumber());
dialogInterface.dismiss();
}
});
builder.show();
}
private void showConfirmDialog(final int position, final String number) {
AlertDialog .Builder builder = new AlertDialog.Builder(context);
View itemView = LayoutInflater.from(context)
.inflate(R.layout.confirm_add_to_cart_layout,null);
final ImageView img_product_dialog = (ImageView)itemView.findViewById(R.id.img_product);
final TextView txt_product_price = (TextView)itemView.findViewById(R.id.txt_cart_product_price);
final TextView txt_product_dialog = (TextView)itemView.findViewById(R.id.txt_cart_product_name);
final ElegantNumberButton enb_amount = (ElegantNumberButton)itemView.findViewById(R.id.txt_amount) ;
requestQueue = Volley.newRequestQueue(context);
final String insertURL = "http://192.168.254.121/itsproject/sendorder.php";
Picasso.with(context).load(foodList.get(position).Link).into(img_product_dialog);
txt_product_dialog.setText(new StringBuilder(foodList.get(position).Name).append(" x").append(number).toString());
final double price1 = (Double.parseDouble(foodList.get(position).Price)* Double.parseDouble(number));
final double finalPrice = price1;
txt_product_price.setText(new StringBuilder("₱").append(price1));
builder.setNegativeButton("CONFIRM", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
try {
mService = Common.getAPI();
Cart cartItem = new Cart();
cartItem.name = txt_product_dialog.getText().toString();
cartItem.amount = Integer.parseInt(number);
cartItem.price = finalPrice;
cartItem.link = foodList.get(position).Link;
StringRequest request = new StringRequest(Request.Method.POST, insertURL, new com.android.volley.Response.Listener<String>() {
#Override
public void onResponse(String response) {
}
}, new com.android.volley.Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> parameters = new HashMap<String,String>();
parameters.put("Name",txt_product_dialog.getText().toString());
parameters.put("Link",foodList.get(position).Link);
parameters.put("Amount", String.valueOf(Integer.parseInt(number)));
parameters.put("Price", String.valueOf(finalPrice));
return parameters;
}
};
requestQueue.add(request);
Common.cartRepository.insertToCart(cartItem);
Log.d("KANZEN_DEBUG", new Gson().toJson(cartItem));
Log.d("DEBUG", new Gson().toJson(request));
Toast.makeText(context, "Successfully Added To Your Order!", Toast.LENGTH_SHORT).show();
} catch (Exception ex) {
Toast.makeText(context, ex.getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
builder.setView(itemView);
builder.show();
}
#Override
public int getItemCount() {
return foodList.size();
}
}
Heres my sendorder.php
<?php
require_once 'db_functions.php';
$db = new DB_Functions();
// json response array
$response = array();
if(isset($_POST['name']) &&
isset($_POST['link']) &&
isset($_POST['amount']) &&
isset($_POST['price']))
{
$name = $_POST['name'];
$link = $_POST['link'];
$amount = $_POST['amount'];
$price = $_POST['price'];
if($db->checkExistUser($name))
{
$response["error_msg"] = "user already exist with this phone number ".$name;
echo json_encode($response);
}
else
{
$order_tbl = $db->SendOrder($name, $link, $amount, $price);
if($order_tbl)
{
$response["name"] = $order_tbl["Name"];
$response["link"] = $order_tbl["Link"];
$response["amount"] = $order_tbl["Amount"];
$response["price"] = $order_tbl["Price"];
echo json_encode($response);
}
else
{
$response["error_msg"] = "Unknown error occurred on sending order!";
echo json_encode($response);
}
}
}
else
{
$response["error_msg"] = "Required parameter (name,link,amount,price) is missing!";
echo json_encode($response);
}
?>
Heres my db_functions.php
<?php
class DB_Functions {
private $conn;
// constructor
function __construct() {
require_once 'db_connect.php';
// connecting to database
$db = new Db_Connect();
$this->conn = $db->connect();
}
// destructor
function __destruct() {
}
/**
* Check user is existed or not
*/
public function checkExistUser($phone) {
$stmt = $this->conn->prepare("SELECT * from User WHERE Phone = ?");
$stmt->bind_param("s", $phone);
$stmt->execute();
$stmt->store_result();
if ($stmt->num_rows > 0) {
// user existed
$stmt->close();
return true;
} else {
// user not existed
$stmt->close();
return false;
}
}
/**
* Storing new user
* returns user details
*/
public function registerNewUser($phone, $name, $birthdate, $address) {
$stmt = $this->conn->prepare("INSERT INTO User(Phone, Name, Birthdate, Address) VALUES(?, ?, ?, ?)");
$stmt->bind_param("ssss", $phone, $name, $birthdate, $address);
$result = $stmt->execute();
$stmt->close();
// check for successful store
if ($result) {
$stmt = $this->conn->prepare("SELECT * FROM User WHERE Phone = ?");
$stmt->bind_param("s", $phone);
$stmt->execute();
$user = $stmt->get_result()->fetch_assoc();
$stmt->close();
return $user;
} else {
return false;
}
}
public function getUserInformation($phone)
{
$stmt = $this->conn->prepare("SELECT * FROM User WHERE phone=?");
$stmt->bind_param("s",$phone);
if($stmt->execute())
{
$user = $stmt->get_result()->fetch_assoc();
$stmt->close();
return $user;
}
else
{
return NULL;
}
}
public function getBanners()
{
$result = $this->conn->query("SELECT * FROM Banner ORDER BY ID LIMIT 3");
$banners = array();
while($item = $result->fetch_assoc())
$banners[] = $item;
return $banners;
}
public function getMenu()
{
$result = $this->conn->query("SELECT * FROM Menu");
$menu = array();
while($item = $result->fetch_assoc())
$menu[] = $item;
return $menu;
}
public function getFoodByMenuID($menuId)
{
$query = "SELECT * FROM Food WHERE MenuId ='".$menuId."'";
$result = $this->conn->query($query);
$foods = array();
while($item = $result->fetch_assoc())
$foods[] = $item;
return $foods;
}
public function SendOrder($name, $link, $amount, $price) {
$stmt = $this->conn->prepare("INSERT INTO order_tbl(Name, Link, Amount, Price) VALUES(?, ?, ?, ?)");
$stmt->bind_param("ssii", $name, $link, $amount, $price);
$result = $stmt->execute();
$stmt->close();
// check for successful store
if ($result) {
$stmt = $this->conn->prepare("SELECT * FROM order_tbl WHERE Name = ?");
$stmt->bind_param("s", $name);
$stmt->execute();
$user = $stmt->get_result()->fetch_assoc();
$stmt->close();
return $user;
} else {
return false;
}
}
}
?>
I have this code in android studio for an app, I am trying to read from a file for the information of the login but anything after BufferedReader is not executing.
both the registration and login page open, the first page in the app i have sa login button and a registration button, when i click on the login button nothng happen, not even checking if the user exist or not
I tried many ways for reading and writing to a file but I couldn't figure out the error
it is not reading anything and not writing any thing, it simply does nothing.
this is the login page
package com.example.admin.projectfinal;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.TextInputEditText;
import android.support.design.widget.TextInputLayout;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.example.admin.projectfinal.val.inputValidation;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.StringTokenizer;
public class LoginActivity extends AppCompatActivity {
private inputValidation InputValidation;
private TextInputLayout IDLayout;
private TextInputLayout PASSWORDlayout;
private TextInputEditText LogID;
private TextInputEditText PASS;
Button SI;
TextView TV;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
getSupportActionBar().hide();
PASS = findViewById(R.id.password);
LogID = findViewById(R.id.idd);
IDLayout = findViewById(R.id.IDLayout);
PASSWORDlayout = findViewById(R.id.PasswordLayout);
TV = findViewById(R.id.tv);
SI = findViewById(R.id.signin);
SI.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
login();
}
});
TV.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Navigate to RegisterActivity
Toast.makeText(LoginActivity.this, "we are in tv.", Toast.LENGTH_LONG).show();
Intent intentRegister = new Intent(LoginActivity.this, RegisterActivity.class);
startActivity(intentRegister);
}
});
InputValidation = new inputValidation(LoginActivity.this);
}
private void login() {
if (!InputValidation.isInputEditTextFilled(LogID, IDLayout, "ID not filled ")) return;
if (!InputValidation.isInputEditTextFilled(PASS, PASSWORDlayout, "Password not filled"))
return;
TextView FileContentTextView = findViewById(R.id.tv_file_content);
try {
File f = new File ("User.txt");
BufferedReader reader = new BufferedReader(new FileReader(f));
if (reader.ready()) {
FileContentTextView.setText("No User registered");
return;
} else {
Toast.makeText(LoginActivity.this, "else", Toast.LENGTH_LONG).show();
boolean found = false;
String role = null;
String line;
while ((line = reader.readLine()) != null) {
Toast.makeText(LoginActivity.this, "while", Toast.LENGTH_LONG).show();
StringTokenizer user = new StringTokenizer(line);
String name = user.nextToken();
String Id = user.nextToken();
String dob = user.nextToken();
String pas = user.nextToken();
String Campus = user.nextToken();
String gender = user.nextToken();
role = user.nextToken();
if (LogID.equals(Id)) {
Toast.makeText(LoginActivity.this, "id is good", Toast.LENGTH_LONG).show();
if (PASS.equals(pas)) {
Toast.makeText(LoginActivity.this, "pass good", Toast.LENGTH_LONG).show();
found = true;
break;
}
}
if (found) {
Toast.makeText(LoginActivity.this, "break.", Toast.LENGTH_LONG).show();
break;
}
}
if (found) {
Toast.makeText(LoginActivity.this, "found", Toast.LENGTH_LONG).show();
if (role.equals("Security")) {
Intent accountsIntent = new Intent(LoginActivity.this, SecurityPage.class);
accountsIntent.putExtra("ID", LogID.getText().toString().trim());
} else {
Intent accountsIntent = new Intent(LoginActivity.this, StudentPage.class);
accountsIntent.putExtra("ID", LogID.getText().toString().trim());
}
} else
reader.close();
}
}catch(IOException e){
e.printStackTrace();
}
}
}
this is the registration code, it has the same problem where anything after the BufferedReader is not executing.
package com.example.admin.projectfinal;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.TextInputEditText;
import android.support.design.widget.TextInputLayout;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.Toast;
import com.example.admin.projectfinal.val.inputValidation;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
public class RegisterActivity extends AppCompatActivity implements View.OnClickListener{
private TextInputLayout textInputLayoutName;
private TextInputLayout textInputLayoutId;
private TextInputLayout textInputLayoutPassword;
private TextInputLayout textInputLayoutDate;
TextInputEditText Name;
TextInputEditText id;
TextInputEditText Password;
TextInputEditText DOB;
Spinner campus;
Spinner Role;
Spinner Gender;
Button btn;
Button Cancel;
private inputValidation InputValidation;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
Name = findViewById(R.id.name);
id = findViewById(R.id.ID);
Password = findViewById(R.id.password);
DOB = findViewById(R.id.dob);
btn = findViewById(R.id.next);
Cancel = findViewById(R.id.cancel);
campus = findViewById(R.id.campus);
Gender = findViewById(R.id.gender);
Role = findViewById(R.id.role);
textInputLayoutName = findViewById(R.id.NameLayout);
textInputLayoutId = findViewById(R.id.IdLayout);
textInputLayoutPassword = findViewById(R.id.PasswordLayout);
textInputLayoutDate = findViewById(R.id.DOBLayout);
//list for campus
String[] CampusList = new String[]{"MainCampus", "SasAlNakhlCampus", "MasdarCampus"};
ArrayAdapter<String> adapter1 = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, CampusList);
campus.setAdapter(adapter1);
//list for gender
String[] gen = new String[]{"Male", "Female"};
ArrayAdapter<String> genAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, gen);
Gender.setAdapter(genAdapter);
//list for role
String[] rolee = new String[]{"Student", "Security"};
ArrayAdapter<String> roleAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, rolee);
Role.setAdapter(roleAdapter);
// Buttons validation
btn.setOnClickListener(this);
Cancel.setOnClickListener(this);
InputValidation = new inputValidation(RegisterActivity.this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.next:
try {
validate();
} catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
break;
case R.id.cancel:
// Navigate to RegisterActivity
Intent intentRegister = new Intent(this, LoginActivity.class);
startActivity(intentRegister);
break;
}
}
private void validate() throws IOException {
boolean filled = true;
if (!InputValidation.isInputEditTextFilled(Name, textInputLayoutName, "Fill Name")) {
filled = false;
return;
}
if (!InputValidation.isInputEditTextFilled(id, textInputLayoutId, "Fill ID")) {
filled = false;
return;
}
if (!InputValidation.isInputEditTextFilled(DOB, textInputLayoutDate, "Fill Date")) {
filled = false;
return;
}
if (!InputValidation.isInputEditTextFilled(Password, textInputLayoutPassword, "Invalid Password")) {
filled = false;
return;
}
if (filled){
//if (!UserInfo.exists()) UserInfo.createNewFile();
String line;
boolean found = false;
BufferedReader reader= new BufferedReader(new FileReader("User.txt"));
Toast.makeText(getBaseContext(), "ready", Toast.LENGTH_LONG).show();
while ((line = reader.readLine()) != null) {
Toast.makeText(getBaseContext(), "while", Toast.LENGTH_LONG).show();
String[] user = line.split(" ");
String name = user[0];
String Id = user[1];
String dob = user[2];
String password = user[3];
String Campus = user[4];
String gender = user[5];
String role = user[6];
if (id.equals(Id)) {
found = true;
Toast.makeText(getBaseContext(), "User Exist", Toast.LENGTH_LONG).show();
break;
}
if (!found) {
// Adds a line to the file
PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter("User.txt")));
writer.append(Name + " " + id + " " + DOB + " " + Password + " "
+ campus.getSelectedItem() + " " + Gender.getSelectedItem() + " " + Role.getSelectedItem() + "/n" );
}
}
reader.close();
}
}
}
Input validation class I used in the code:
package com.example.admin.projectfinal.val;
import android.app.Activity;
import android.content.Context;
import android.support.design.widget.TextInputEditText;
import android.support.design.widget.TextInputLayout;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
public class inputValidation {
private static Context context;
/**
* constructor
*
* #param context
*/
public inputValidation(Context context) {
this.context = context;
}
/**
* method to check InputEditText filled .
*
* #param textInputEditText
* #param textInputLayout
* #param message
* #return
*/
public static boolean isInputEditTextFilled(TextInputEditText textInputEditText, TextInputLayout textInputLayout, String message) {
String value = textInputEditText.getText().toString().trim();
if (value.isEmpty()) {
textInputLayout.setError(message);
hideKeyboardFrom(textInputEditText);
return false;
} else {
textInputLayout.setErrorEnabled(false);
}
return true;
}
/**
* method to Hide keyboard
*
* #param view
*/
private static void hideKeyboardFrom(View view) {
InputMethodManager imm = (InputMethodManager) context.getSystemService(Activity.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
}
}
I am trying to make an app which uses last.fm's web API, sends a query for similar artists and returns all the names of the similar artists. It seems as though I manage to connect and get the xml response properly. However, I cannot extract the value of the name-attribute. I am using artistName = xmlData.getAttributeValue(null, "name"); but all it gives me is null.
import android.app.Activity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import java.util.*;
#SuppressWarnings("FieldCanBeLocal")
public class MainActivity extends Activity implements Observer {
private final String INPUTERROR = "Invalid/missing artist name.";
private NetworkCommunication nc;
private ArrayList<String> list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
nc = new NetworkCommunication();
nc.register(this);
list = new ArrayList<>();
ListView lv = (ListView)findViewById(R.id.ListView_similarArtistsList);
ArrayAdapter adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, list);
lv.setAdapter(adapter);
}
public void searchButton_Clicked(View v){
EditText inputField = (EditText)findViewById(R.id.editText_artistName);
String searchString = inputField.getText().toString();
searchString = cleanSearchString(searchString);
if(validateSearchString(searchString)){
nc.setSearchString(searchString);
nc.execute();
}
else{
Toast.makeText(MainActivity.this, INPUTERROR, Toast.LENGTH_SHORT).show();
}
}
private String cleanSearchString(String oldSearchString){
String newString = oldSearchString.trim();
newString = newString.replace(" ", "");
return newString;
}
private boolean validateSearchString(String searchString){
boolean rValue = true;
if(TextUtils.isEmpty(searchString)){
rValue = false;
}
return rValue;
}
#Override
public void update(String artistName) {
list.add(artistName);
}
}
Here is my Network Communications class:
import android.os.AsyncTask;
import android.util.Log;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
#SuppressWarnings("FieldCanBeLocal")
class NetworkCommunication extends AsyncTask<Object, String, Integer> implements Subject {
private final String MYAPIKEY = "--------------------------";
private final String ROOT = "http://ws.audioscrobbler.com/2.0/";
private final String METHOD = "?method=artist.getsimilar";
private ArrayList<Observer> observers;
private int amountOfArtists = 0;
private String foundArtistName;
private String searchString;
NetworkCommunication(){
observers = new ArrayList<>();
}
void setSearchString(String newSearchString){
searchString = newSearchString;
}
private XmlPullParser sendRequest(){
try{
URL url = new URL(ROOT + METHOD + "&artist=" + searchString + "&api_key=" + MYAPIKEY);
XmlPullParser receivedData = XmlPullParserFactory.newInstance().newPullParser();
receivedData.setInput(url.openStream(), null);
return receivedData;
}
catch (IOException | XmlPullParserException e){
Log.e("ERROR", e.getMessage(), e);
}
return null;
}
private int tryProcessData(XmlPullParser xmlData){
int artistsFound = 0;
String artistName;
int eventType;
try{
while ((eventType = xmlData.next()) != XmlPullParser.END_DOCUMENT) {
if (eventType == XmlPullParser.START_TAG) {
if(xmlData.getName().equals("name")){
artistName = xmlData.getAttributeValue(null, "name");
publishProgress(artistName);
artistsFound++;
}
}
}
}
catch (IOException | XmlPullParserException e){
Log.e("ERROR", e.getMessage(), e);
}
if (artistsFound == 0) {
publishProgress();
}
return artistsFound;
}
#Override
protected Integer doInBackground(Object... params) {
XmlPullParser data = sendRequest();
if(data != null){
return tryProcessData(data);
}
else{
return null;
}
}
#Override
protected void onProgressUpdate(String... values){
/*
if (values.length == 0) {
//No data found...
}
*/
if (values.length == 1) {
setFoundArtistName(values[0]);
notifyObserver();
}
super.onProgressUpdate(values);
}
private void setFoundArtistName(String newArtistName){
foundArtistName = newArtistName;
}
#Override
public void register(Observer newObserver) {
observers.add(newObserver);
}
#Override
public void unregister(Observer deleteObserver) {
observers.remove(deleteObserver);
}
#Override
public void notifyObserver() {
for (Observer o : observers) {
Log.i("my tag.... ", "name = " + foundArtistName);
o.update(foundArtistName);
}
}
}
Here's a screenshot of the xml response in Google Chrome:
The only thing I am interested in extracting at this moment is the the value of the Name-Element.
I am logging the value of foundArtistName (in the method notifyObserver) it gives me A LOT of "my tag.... name = null my tag.... name = null my tag.... name = null etc.."
EDIT: I tried using getText() instead of getAttributeValue(), but it also gives me null.
I found the solution. I was using: artistName = xmlData.getAttributeValue(null, "name");, when I really should've used: artistName = xmlData.nextText();
I am also getting ArrayListIndexOutofBound when I am pressing list item when the orientation is changed.As far my knowledge of android I have written Parcelable code correctly.But I think my issues are with the recycler view setup.I am confused with two declaration of my adapter.Help me
MainActivity.class
package com.reader.ashishyadav271.hackernewsmaterial;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Parcelable;
import android.os.PersistableBundle;
import android.support.v4.util.LruCache;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;
import android.widget.Toast;
import com.wang.avi.AVLoadingIndicatorView;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class MainActivity extends AppCompatActivity implements MyCustomAdapter.ClickListener {
private static final String STATE_LIST = "state_list";
Map<Integer, String> articleURLs = new HashMap<>();
Map<Integer, String> articleTitles = new HashMap<>();
Map<Integer, String> articleDates =new HashMap<>();
Map<Integer, String> articleAuthors =new HashMap<>();
ArrayList<Integer> articleIds=new ArrayList<>();
SQLiteDatabase articlesDB;
ArrayList<Information> data=new ArrayList<>();
ArrayList<String> titles=new ArrayList<>();
ArrayList<String> urls=new ArrayList<>();
ArrayList<String> authors=new ArrayList<>();
ArrayList<String> dateAndTimes=new ArrayList<>();
MyCustomAdapter adapter;
RecyclerView recyclerView;
AVLoadingIndicatorView av;
List<DownloadTask> tasks;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
av= (AVLoadingIndicatorView) findViewById(R.id.avloadingIndicatorView);
av.setVisibility(View.INVISIBLE);
tasks = new ArrayList<>();
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
recyclerView= (RecyclerView) findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
recyclerView.addItemDecoration(new SimpleDividerItemDecoration(
getApplicationContext()
));
articlesDB = this.openOrCreateDatabase("Articles", MODE_PRIVATE, null);
articlesDB.execSQL("CREATE TABLE IF NOT EXISTS article (id INTEGER PRIMARY KEY," +
" articleId INTEGER," +
" url VARCHAR," +
" title VARCHAR," +
" author VARCHAR," +
" date VARCHAR)");
if(savedInstanceState != null) {
data=savedInstanceState.getParcelableArrayList(STATE_LIST);
adapter=new MyCustomAdapter(getApplicationContext(),data);
adapter.setClickListener(this);
recyclerView.setAdapter(adapter);
}else{
if (isOnline()) {
requestData("https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty");
} else {
updateDisplay();
Toast.makeText(this, "Network isn't available", Toast.LENGTH_LONG).show();
}
}
//adapter=new MyCustomAdapter(getApplicationContext(),getData());
//adapter.setClickListener(this);
//recyclerView.setAdapter(adapter);
}
protected boolean isOnline() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
} else {
return false;
}
}
private void requestData(String uri) {
DownloadTask task = new DownloadTask();
task.execute(uri);
}
#Override
public void itemClicked(View view, int position) {
Intent i = new Intent(getApplicationContext(), Main2Activity.class);
i.putExtra("articleUrl", urls.get(position));
startActivity(i);
}
protected void updateDisplay() {
adapter=new MyCustomAdapter(getApplicationContext(),getData());
adapter.setClickListener(this);
recyclerView.setAdapter(adapter);;
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelableArrayList(STATE_LIST, data);
}
public class DownloadTask extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
if (tasks.size() == 0) {
av.setVisibility(View.VISIBLE);
}
tasks.add(this);
}
#Override
protected String doInBackground(String... urls) {
String result = "";
URL url;
HttpURLConnection urlConnection;
try {
url = new URL(urls[0]);
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(in);
int data = reader.read();
while (data != -1) {
char current = (char) data;
result += current;
data = reader.read();
}
JSONArray jsonArray = new JSONArray(result);
articlesDB.execSQL("DELETE FROM article");
for (int i = 0; i < 15; i++) {
String articleId = jsonArray.getString(i);
url = new URL("https://hacker-news.firebaseio.com/v0/item/" + articleId + ".json?print=pretty");
urlConnection = (HttpURLConnection) url.openConnection();
in = urlConnection.getInputStream();
reader = new InputStreamReader(in);
data = reader.read();
String articleInfo = "";
while (data != -1 ) {
char current = (char) data;
articleInfo += current;
data = reader.read();
}
JSONObject jsonObject = new JSONObject(articleInfo);
String articleTitle = jsonObject.getString("title");
String articleURL = jsonObject.getString("url");
String articleDate=jsonObject.getString("time");
String articleAuthor=jsonObject.getString("by");
long unixSeconds = Long.valueOf(articleDate);
Date date = new Date(unixSeconds*1000L); // *1000 is to convert seconds to milliseconds
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss"); // the format of your date
String formattedarticleDate = sdf.format(date);
articleIds.add(Integer.valueOf(articleId));
articleTitles.put(Integer.valueOf(articleId), articleTitle);
articleURLs.put(Integer.valueOf(articleId), articleURL);
articleDates.put(Integer.valueOf(articleId), formattedarticleDate);
articleAuthors.put(Integer.valueOf(articleId), articleAuthor);
String sql = "INSERT INTO article (articleId, url, title, author, date) VALUES (? , ? , ? , ?, ?)";
SQLiteStatement statement = articlesDB.compileStatement(sql);
statement.bindString(1, articleId);
statement.bindString(2, articleURL);
statement.bindString(3, articleTitle);
statement.bindString(4, articleAuthor);
statement.bindString(5, formattedarticleDate);
statement.execute();
}
}catch (Exception e) {
e.printStackTrace();
}
return result;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
tasks.remove(this);
if (tasks.size() == 0) {
av.setVisibility(View.INVISIBLE);
}
updateDisplay();
}
}
private List<Information> getData() {
/*List<Information> data=new ArrayList<>();
for(int i=0;i<20;i++){
titles.add(i,"Wikileaks Asssange wins UN ruling on arbitrary detention");
url.add(i,"https://www.google.co.in/search?q=best+custom+list+row");
date.add(i,"3 hrs");
author.add(i,"aburan28");
}
for(int i=0;i<20;i++){
Information current=new Information();
current.title=titles.get(i);
current.url=url.get(i);
current.author=author.get(i);
current.date=date.get(i);
data.add(current);
}
return data;*/
Cursor c = articlesDB.rawQuery("SELECT * FROM article", null);
try {
int urlIndex = c.getColumnIndex("url");
int titleIndex = c.getColumnIndex("title");
int authorIndex = c.getColumnIndex("author");
int dateIndex = c.getColumnIndex("date");
c.moveToFirst();
titles.clear();
//urls.clear();
authors.clear();
dateAndTimes.clear();
int i=0;
while (c != null) {
titles.add(c.getString(titleIndex));
urls.add(c.getString(urlIndex));
authors.add(c.getString(authorIndex));
dateAndTimes.add(c.getString(dateIndex));
Information current=new Information();
current.title=titles.get(i);
current.url=urls.get(i);
current.author=authors.get(i);
current.date = dateAndTimes.get(i);
data.add(current);
i++;
c.moveToNext();
}
}catch (Exception e) {
e.printStackTrace();
}finally {
c.close();
}
return data;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
startActivity(new Intent(getApplicationContext(),SettingsActivity.class));
return true;
}
if (id == R.id.action_about) {
startActivity(new Intent(getApplicationContext(),About.class));
return true;
}
return super.onOptionsItemSelected(item);
}
}
Information.class
package com.reader.ashishyadav271.hackernewsmaterial;
import android.os.Parcel;
import android.os.Parcelable;
public class Information implements Parcelable {
public String title;
public String author;
public String date;
public String url;
public Information(){
}
protected Information(Parcel in) {
title = in.readString();
author = in.readString();
date = in.readString();
url = in.readString();
}
public static final Creator<Information> CREATOR = new Creator<Information>() {
#Override
public Information createFromParcel(Parcel in) {
return new Information(in);
}
#Override
public Information[] newArray(int size) {
return new Information[size];
}
};
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(title);
dest.writeString(author);
dest.writeString(date);
dest.writeString(url);
}
}
Log Cat Error
02-06 14:52:58.106 8369-8369/com.reader.ashishyadav271.hackernewsmaterial E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.reader.ashishyadav271.hackernewsmaterial, PID: 8369
java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)
at java.util.ArrayList.get(ArrayList.java:308)
at com.reader.ashishyadav271.hackernewsmaterial.MainActivity.itemClicked(MainActivity.java:137)
at com.reader.ashishyadav271.hackernewsmaterial.MyCustomAdapter$MyViewHolder.onClick(MyCustomAdapter.java:77)
at android.view.View.performClick(View.java:4471)
at android.view.View$PerformClick.run(View.java:18778)
at android.os.Handler.handleCallback(Handler.java:808)
at android.os.Handler.dispatchMessage(Handler.java:103)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:5345)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:828)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:644)
at dalvik.system.NativeStart.main(Native Method)
Now I get it after years.I would have simply used.
FLAG_ACTIVITY_CLEAR_TOP - If set, and the activity being launched is already running in the current task, then instead of launching a new instance of that activity, all of the other activities on top of it will be closed and this Intent will be delivered to the (now on top) old activity as a new Intent.
I need to show toast message when the server is not responding
when I press the login button, some parameters are passed to AgAppMenu screen which use url connection to server and get xml response in AgAppHelperMethods screen. The
probelm is when the server is busy or the network is not avaibale, I can't show toast message on catch block although it shows the log message.
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent ;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class LoginScreen extends Activity implements OnClickListener {
EditText mobile;
EditText pin;
Button btnLogin;
Button btnClear;
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.agapplogin);
TextView lblMobileNo = (TextView) findViewById(R.id.lblMobileNo);
lblMobileNo.setTextColor(getResources()
.getColor(R.color.text_color_red));
mobile = (EditText) findViewById(R.id.txtMobileNo);
TextView lblPinNo = (TextView) findViewById(R.id.lblPinNo);
lblPinNo.setTextColor(getResources().getColor(R.color.text_color_red));
pin = (EditText) findViewById(R.id.txtPinNo);
btnLogin = (Button) findViewById(R.id.btnLogin);
btnClear = (Button) findViewById(R.id.btnClear);
btnLogin.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
postLoginData();
}
});
btnClear.setOnClickListener(new OnClickListener() {
public void onClick(View v)
{
cleartext();
}
});
/*
*
* btnClear.setOnClickListener(new OnClickListener() { public void
* onClick(View arg0) {
*
* } });
*/
}
public void postLoginData()
{
if (pin.getTextSize() == 0 || mobile.getTextSize() == 0) {
AlertDialog.Builder altDialog = new AlertDialog.Builder(this);
altDialog.setMessage("Please Enter Complete Information!");
} else {
Intent i = new Intent(this.getApplicationContext(), AgAppMenu.class);
Bundle bundle = new Bundle();
bundle.putString("mno", mobile.getText().toString());
bundle.putString("pinno", pin.getText().toString());
i.putExtras(bundle);
startActivity(i);
}
}
#Override
public void onClick(View v) {
}
public void cleartext() {
{
pin.setText("");
mobile.setText("");
}
}
}
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class AgAppMenu extends Activity {
String mno, pinno;
private String[][] xmlRespone;
Button btnMiniStatement;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.agappmenu);
mno = getIntent().getExtras().getString("mno");
pinno = getIntent().getExtras().getString("pinno");
setTitle("Welcome to the Ag App Menu");
AgAppHelperMethods agapp =new AgAppHelperMethods();
// xmlRespone = AgAppHelperMethods.AgAppXMLParser("AG_IT_App/AgMainServlet?messageType=LOG&pin=" + pinno + "&mobile=" + mno + "&source=" + mno + "&channel=INTERNET");
xmlRespone = agapp.AgAppXMLParser("AG_IT_App/AgMainServlet?messageType=LOG&pin=" + pinno + "&mobile=" + mno + "&source=" + mno + "&channel=INTERNET");
import java.net.URL;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import android.view.View;
import android.view.View.OnKeyListener;
public class AgAppHelperMethods extends Activity {
private static final String LOG_TAG = null;
private static AgAppHelperMethods instance = null;
public static String varMobileNo;
public static String varPinNo;
String[][] xmlRespone = null;
boolean flag = true;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.agapphelpermethods);
}
protected AgAppHelperMethods() {
}
public static AgAppHelperMethods getInstance() {
if (instance == null) {
instance = new AgAppHelperMethods();
}
return instance;
}
public static String getUrl() {
String url = "https://demo.accessgroup.mobi/";
return url;
}
public String[][] AgAppXMLParser(String parUrl) {
String _node, _element;
String[][] xmlRespone = null;
try {
String url = AgAppHelperMethods.getUrl() + parUrl;
URL finalUrl = new URL(url);
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new InputSource(finalUrl.openStream()));
doc.getDocumentElement().normalize();
NodeList list = doc.getElementsByTagName("*");
_node = new String();
_element = new String();
xmlRespone = new String[list.getLength()][2];
// this "for" loop is used to parse through the
// XML document and extract all elements and their
// value, so they can be displayed on the device
for (int i = 0; i < list.getLength(); i++) {
Node value = list.item(i).getChildNodes().item(0);
_node = list.item(i).getNodeName();
_element = value.getNodeValue();
xmlRespone[i][0] = _node;
xmlRespone[i][1] = _element;
}// end for
throw new ArrayIndexOutOfBoundsException();
}// end try
// will catch any exception thrown by the XML parser
catch (Exception e) {
Toast.makeText(AgAppHelperMethods.this,
"error server not responding " + e.getMessage(),
Toast.LENGTH_SHORT).show();
Log.e(LOG_TAG, "CONNECTION ERROR FUNDAMO SERVER NOT RESPONDING", e);
}
// Log.e(LOG_TAG, "CONNECTION ERROR FUNDAMO SERVER NOT RESPONDING", e);
return xmlRespone;
}
`
AgAppHelperMethods isn't really an Activity. You've derived this class from Activity, but then you've created Singleton management methods (getInstance()) and you are instantiating it yourself. This is bad. Don't do this.
Normally Android controls the instantiation of activities. You don't ever create one yourself (with new).
It looks to me like AgAppHelperMethods just needs to be a regular Java class. It doesn't need to inherit from anything. Remove also the lifecycle methods like onCreate().
Now you will have a problem with the toast, because you need a context for that and AgAppHelperMethods isn't a Context. To solve that you can add Context as a parameter to AgAppXMLParser() like this:
public String[][] AgAppXMLParser(Context context, String parUrl) {
...
// Now you can use "context" to create your toast.
}
When you call AgAppXMLParser() from AgAppMenu just pass "this" as the context parameter.