on Sunday, August 31, 2014


So, what I am trying to do is to make a semi-automatic page monitor which alerts user when some part of screen has changed, and the biggest benefit of my app is that user can record some actions because some login or register forms are changing by clicking JavaScript element, not just by refreshing. What I've done so far is that I made zoomable WebView and programmed a button which starts and stops touch movement recording. Everything works like a charm, except when user presses JavaScript spinner. When it appears, my app stops recording touches, and also, android layout buttons hide. So, what I want to do is to force my touch recording system to respond to every possible element, event it is written in JavaScript. Here is my code:



package com.example.automatikaandroidui;

import java.util.ArrayList;

import android.support.v7.app.ActionBarActivity;
import android.graphics.Color;
import android.graphics.Point;
import android.graphics.PointF;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends ActionBarActivity implements OnClickListener, OnTouchListener {

WebView webView;
Button mygtukasSeka;
boolean isPressed = false;
boolean halfWay = false;
boolean eile = false;
ArrayList<PointF> masyvas = null;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
masyvas = new ArrayList<PointF>();

webView = (WebView)findViewById(R.id.webView1);
webView.loadUrl("https://www.eregitra.lt/viesa/interv/Index.php");
webView.getSettings().setBuiltInZoomControls(true);
webView.getSettings().setLoadWithOverviewMode(true);
webView.getSettings().setUseWideViewPort(true);
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebChromeClient(new WebChromeClient());
webView.setOnTouchListener(this);


mygtukasSeka = (Button)findViewById(R.id.mygtukas_seka);
mygtukasSeka.setOnClickListener(this);
}

@Override
public void onClick(View v) {

switch(v.getId()){

case R.id.mygtukas_seka: {
TextView notify = (TextView)findViewById(R.id.ispek_irasyma);

if(!isPressed){

notify.setTextColor(Color.RED);
notify.setText("Įrašoma...");
isPressed = true;

}

else {
notify.setText("");
isPressed = false;
}
}

}

}

@Override
public boolean onTouch(View v, MotionEvent event) {

switch (event.getActionMasked()){

case MotionEvent.ACTION_DOWN : {
if(!halfWay && isPressed)
halfWay = true;
}

case MotionEvent.ACTION_UP : {
if(halfWay && isPressed){
PointF taskas = new PointF(event.getX(),event.getY());
masyvas.add(taskas);
halfWay = false;
Toast.makeText(MainActivity.this, taskas.x+" "+taskas.y, Toast.LENGTH_SHORT).show();
Toast.makeText(MainActivity.this, masyvas.size()+"", Toast.LENGTH_SHORT).show();
}
}

}

if(isPressed){
if(eile)
eile = false;
else eile = true;
}

return eile;
}

}


And here are some screenshots : Here is the registration form. When you press on B spinner appears, and when you change different element from it, all page refreshes. As you can see there are three buttons on the bottom, and the middle one called Seka records touches.


http://i.stack.imgur.com/UJxjg.png


There is spinner that I've talked before. Ignore toast message


http://i.stack.imgur.com/ekWTo.png


Thanks in advance ! :)




This my code used for usage of key store to save an arbitrary text as a key in the keystore how I am getting the "Keystore is not initialized error", how can I fix this?



public void secretKeyGeneration(View view) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException {

KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
byte[] sek = "eru9tyighw34ilty348934i34uiq34q34ri".getBytes();
SecretKey sk = new SecretKeySpec(sek, 0, sek.length, "AES");
char[] password = "keystorepassword".toCharArray();
KeyStore.ProtectionParameter protParam =
new KeyStore.PasswordProtection(password);

KeyStore.SecretKeyEntry skEntry = new KeyStore.SecretKeyEntry(sk);
ks.setEntry("secretKeyAlias", skEntry, protParam);

}



What I am trying to accomplish is, starting from an app's ActivityInfo (third party app), I would like to launch it from my Service in the state it was. In the same way that if an user presses the home button and there touches, for example, Whatsapp's icon, Whatsapp will launch to the conversation he previously was. I have managed to launch any app. What I don't know is how to launch the app to the previous state, that is, the particular conversation I (or the user) was in -assuming it is still in memory, of course.


I first tried:



ActivityInfo app = (ActivityInfo) getActivityInfo();
String packName = app.packageName;
Intent appIntent = pm.getLaunchIntentForPackage(packName);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(appIntent);


Then I tried:



ActivityInfo app = (ActivityInfo) getActivityInfo();
String packName = app.packageName;
Intent appIntent = pm.getLaunchIntentForPackage(packName);
appIntent.setFlags(0);
appIntent.setPackage(null);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(appIntent);


I have also tried:



ActivityInfo app = (ActivityInfo) getActivityInfo();
Intent appIntent = new Intent();
appIntent.setComponent(new ComponentName(app.applicationInfo.packageName, app.name));
appIntent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(appIntent);


So, does anyone know how to achieve this?




I am making a system (Android) for my software engineering class and this is a brief description of the system: It is an app for a gym that shows the list of the workouts that can be done. This is the step-by-step processes that I made for the system:




  1. Admin log in (in order to access the app- only the admin can open the app because the app serves as a kioks) THIS PART IS DONE




  2. Current Users page (this is a page that shows who are currently using the app in the gym) this part is not done yet but I am doing this part by database: DESCRIPTION: a. users are required to register to the app (done by database: involves username and password columns) b. if the user is registered and ready to add into current users they will login their username and password




  3. User Workout page (after logging in from current users page this page will show) this part is not done yet DESCRIPTION: a. This page shows the user's history workout (I need a suggestion on how will I record the workout history, is it from database?) b. If the user wants a NEW WORKOUT it will display a ListView of workouts (please read this, this is where I have a hard time) i. Each Workout has: (name, muscletype, rating, machineOrNot, videopath) ii. I am having a hard time putting many workouts in a database, I tried parsing it from XML file and somewhat I know the entries get inserted successfully but i cant make it into the listview for nullpointerexception error




I really need some advices in order to successfully program the system. Also, each workouts has a video in what way I can link it to each workouts?


Thank you all!




Im trying to export android apk with proguard, however this error occured :



Users/thanhnguyen/Documents/mr thao's music/android-sdk-macosx/tools/proguard/bin/proguard.sh: line 10: "/Users/thanhnguyen/Documents/mr thao's music/android-sdk-macosx/tools/proguard": No such file or directory
Unable to access jarfile /Users/thanhnguyen/Documents/mr
at com.android.ide.eclipse.adt.internal.build.BuildHelper.runProguard(BuildHelper.java:623)
at com.android.ide.eclipse.adt.internal.project.ExportHelper.exportReleaseApk(ExportHelper.java:259)
... 4 more


It seems that I must configure file proguard.sh, the default is :



PROGUARD_HOME=`dirname "$0"`/..

java -jar $PROGUARD_HOME/lib/proguard.jar "$@"


My proguard.jar is at : /Users/thanhnguyen/Documents/mr thao's music/android-sdk-macosx/tools/proguard on Mac OS.


I tried to set but didn't work :



PROGUARD_HOME="\"/Users/thanhnguyen/Documents/mr thao's music/android-sdk-macosx/tools/proguard\""

java -jar "$PROGUARD_HOME/lib/proguard.jar" "$@"


How could I change proguard.sh, if not change, what could be the rearson for proguard error?


Thanks a lot!




Hi everyone i start Learning android and i want to make a login registration system with my app but is not working properly here the code where i think i've got an error.


PHP LOGIN SCRIPT :



<?php

//load and connect to MySQL database stuff
require("config.inc.php");

if (!empty($_POST)) {
//gets user's info based off of a username.
$query = "
SELECT
id,
username,
password
FROM users
WHERE
username = :username
";

$query_params = array(
':username' => $_POST['username']
);


try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch (PDOException $ex) {
// For testing, you could use a die and message.
//die("Failed to run query: " . $ex->getMessage());

//or just use this use this one to product JSON data:
$response["success"] = 0;
$response["message"] = "Database Error1. Please Try Again!";
die(json_encode($response));

}

//This will be the variable to determine whether or not the user's information is correct.
//we initialize it as false.
$validated_info = false;

//fetching all the rows from the query
$row = $stmt->fetch();
if ($row) {
//if we encrypted the password, we would unencrypt it here, but in our case we just
//compare the two passwords
if ($_POST['password'] === $row['password']) {
$login_ok = true;
}
}

// If the user logged in successfully, then we send them to the private members-only page
// Otherwise, we display a login failed message and show the login form again
if ($login_ok) {
$response["success"] = 1;
$response["message"] = "Login successful!";
die(json_encode($response));
} else {
$response["success"] = 0;
$response["message"] = "Invalid Credentials!";
die(json_encode($response));
}
} else {
$response["message"] = "Enter username and password!";
die(json_encode($response));
}
?>
<h1>Login</h1>
<form action="login.php" method="post">
Username:<br />
<input type="text" name="username" placeholder="username" />
<br /><br />
Password:<br />
<input type="password" name="password" placeholder="password" value="" />
<br /><br />
<input type="submit" value="Login" />
</form>
<a href="register.php">Register</a>
<?php


?>


LoginActivity :



public class LoginActivity extends ActionBarActivity {
Button btnLogin;
Button btnLinkToRegister;
EditText inputEmail;
EditText inputPassword;
TextView loginErrorMsg;

private ProgressDialog pDialog;

JSONParser jsonParser = new JSONParser();

// JSON Response node names
private static String KEY_SUCCESS = "success";
private static String KEY_ERROR = "error";
private static String KEY_ERROR_MSG = "error_msg";
private static String KEY_UID = "uid";
private static String KEY_NAME = "name";
private static String KEY_EMAIL = "email";
private static String KEY_CREATED_AT = "created_at";
private static final String TAG_MESSAGE = "message";

// Testing on emulator
private static String LOGIN_URL = "http://10.0.2.2/webservice/login.php";

@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
getSupportActionBar().hide();
setContentView(R.layout.login);

// Importing all assets like buttons, text fields
inputEmail = (EditText) findViewById(R.id.loginEmail);
inputPassword = (EditText) findViewById(R.id.loginPassword);
btnLogin = (Button) findViewById(R.id.btnLogin);
btnLinkToRegister = (Button) findViewById(R.id.btnLinkToRegisterScreen);
loginErrorMsg = (TextView) findViewById(R.id.login_error);

// Login button Click Event
btnLogin.setOnClickListener(new View.OnClickListener() {

public void onClick(View view) {
new LoginProcess().execute();

}
});

// Link to Register Screen
btnLinkToRegister.setOnClickListener(new View.OnClickListener() {

public void onClick(View view) {
Intent i = new Intent(getApplicationContext(),
RegisterActivity.class);
startActivity(i);
finish();
}
});

}

private class LoginProcess extends AsyncTask<String, String, String> {

@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(LoginActivity.this);
pDialog.setMessage("Attempting login...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();

}

@Override
protected String doInBackground(String... args) {
// Check for success tag
int success;
String username = inputEmail.getText().toString();
String password = inputPassword.getText().toString();
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", username));
params.add(new BasicNameValuePair("password", password));

Log.d("request!", "starting");
// getting product details by making HTTP request
JSONObject json = jsonParser.makeHttpRequest(LOGIN_URL, "POST",
params);

// check your log for json response
Log.d("Login attempt", json.toString());

// json success tag
success = json.getInt(KEY_SUCCESS);
if (success == 1) {
Log.d("Login Successful!", json.toString());
Intent i = new Intent(LoginActivity.this,
MainActivity.class);
finish();
startActivity(i);
return json.getString(TAG_MESSAGE);
} else {
Log.d("Login Failure!", json.getString(TAG_MESSAGE));
return json.getString(TAG_MESSAGE);

}
} catch (JSONException e) {
e.printStackTrace();
}

return null;
}

/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once product deleted
pDialog.dismiss();
if (file_url != null) {
Toast.makeText(LoginActivity.this, file_url, Toast.LENGTH_LONG).show();
}

}

}
}


JSONParser Class:



public class JSONParser {

static InputStream is = null;
static JSONObject jObj = null;
static String json = "";

// constructor
public JSONParser() {

}

public JSONObject getJSONFromUrl(String url, List<NameValuePair> params) {

// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));

HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();

} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "n");
}
is.close();
json = sb.toString();
Log.e("JSON", json);
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}

// try parse the string to a JSON object
Log.d("JSON Parser", json);
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}

// return JSON String
return jObj;

}

public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {

// check for request method
if(method == "POST"){
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));

HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();

}else if(method == "GET"){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);

HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}

} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}

// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}

// return JSON String
return jObj;

}
}


When i want to login with the right username and password it's working but if i put right username and wrong password i've got an error . But if i delete query_params at : $result = $stmt->execute($query_params);


I don't have any errors but i can't login anymore


The logcat :



08-31 10:40:39.885: E/Trace(1239): error opening trace file: No such file or directory (2)
08-31 10:40:40.785: D/dalvikvm(1239): GC_FOR_ALLOC freed 118K, 2% free 10936K/11143K, paused 55ms, total 57ms
08-31 10:40:40.845: I/dalvikvm-heap(1239): Grow heap (frag case) to 13.346MB for 2764816-byte allocation
08-31 10:40:40.954: D/dalvikvm(1239): GC_CONCURRENT freed 1K, 2% free 13635K/13895K, paused 24ms+6ms, total 108ms
08-31 10:40:41.334: D/libEGL(1239): loaded /system/lib/egl/libEGL_emulation.so
08-31 10:40:41.345: D/(1239): HostConnection::get() New Host Connection established 0x2a126450, tid 1239
08-31 10:40:41.357: D/libEGL(1239): loaded /system/lib/egl/libGLESv1_CM_emulation.so
08-31 10:40:41.376: D/libEGL(1239): loaded /system/lib/egl/libGLESv2_emulation.so
08-31 10:40:41.455: W/EGL_emulation(1239): eglSurfaceAttrib not implemented
08-31 10:40:41.465: D/OpenGLRenderer(1239): Enabling debug mode 0
08-31 10:40:45.545: D/request!(1239): starting
08-31 10:40:45.645: W/EGL_emulation(1239): eglSurfaceAttrib not implemented
08-31 10:40:48.205: E/JSON Parser(1239): Error parsing data org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject
08-31 10:40:48.355: W/dalvikvm(1239): threadid=11: thread exiting with uncaught exception (group=0x40a13300)
08-31 10:40:48.754: E/AndroidRuntime(1239): FATAL EXCEPTION: AsyncTask #1
08-31 10:40:48.754: E/AndroidRuntime(1239): java.lang.RuntimeException: An error occured while executing doInBackground()
08-31 10:40:48.754: E/AndroidRuntime(1239): at android.os.AsyncTask$3.done(AsyncTask.java:299)
08-31 10:40:48.754: E/AndroidRuntime(1239): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
08-31 10:40:48.754: E/AndroidRuntime(1239): at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
08-31 10:40:48.754: E/AndroidRuntime(1239): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
08-31 10:40:48.754: E/AndroidRuntime(1239): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
08-31 10:40:48.754: E/AndroidRuntime(1239): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
08-31 10:40:48.754: E/AndroidRuntime(1239): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
08-31 10:40:48.754: E/AndroidRuntime(1239): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
08-31 10:40:48.754: E/AndroidRuntime(1239): at java.lang.Thread.run(Thread.java:856)
08-31 10:40:48.754: E/AndroidRuntime(1239): Caused by: java.lang.NullPointerException
08-31 10:40:48.754: E/AndroidRuntime(1239): at com.example.diycenter.LoginActivity$LoginProcess.doInBackground(LoginActivity.java:118)
08-31 10:40:48.754: E/AndroidRuntime(1239): at com.example.diycenter.LoginActivity$LoginProcess.doInBackground(LoginActivity.java:1)
08-31 10:40:48.754: E/AndroidRuntime(1239): at android.os.AsyncTask$2.call(AsyncTask.java:287)
08-31 10:40:48.754: E/AndroidRuntime(1239): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
08-31 10:40:48.754: E/AndroidRuntime(1239): ... 5 more
08-31 10:40:51.844: E/WindowManager(1239): Activity com.example.diycenter.LoginActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@4148a190 that was originally added here
08-31 10:40:51.844: E/WindowManager(1239): android.view.WindowLeaked: Activity com.example.diycenter.LoginActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@4148a190 that was originally added here
08-31 10:40:51.844: E/WindowManager(1239): at android.view.ViewRootImpl.<init>(ViewRootImpl.java:374)
08-31 10:40:51.844: E/WindowManager(1239): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:292)
08-31 10:40:51.844: E/WindowManager(1239): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:224)
08-31 10:40:51.844: E/WindowManager(1239): at android.view.WindowManagerImpl$CompatModeWrapper.addView(WindowManagerImpl.java:149)
08-31 10:40:51.844: E/WindowManager(1239): at android.view.Window$LocalWindowManager.addView(Window.java:547)
08-31 10:40:51.844: E/WindowManager(1239): at android.app.Dialog.show(Dialog.java:277)
08-31 10:40:51.844: E/WindowManager(1239): at com.example.diycenter.LoginActivity$LoginProcess.onPreExecute(LoginActivity.java:96)
08-31 10:40:51.844: E/WindowManager(1239): at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586)
08-31 10:40:51.844: E/WindowManager(1239): at android.os.AsyncTask.execute(AsyncTask.java:534)
08-31 10:40:51.844: E/WindowManager(1239): at com.example.diycenter.LoginActivity$1.onClick(LoginActivity.java:69)
08-31 10:40:51.844: E/WindowManager(1239): at android.view.View.performClick(View.java:4084)
08-31 10:40:51.844: E/WindowManager(1239): at android.view.View$PerformClick.run(View.java:16966)
08-31 10:40:51.844: E/WindowManager(1239): at android.os.Handler.handleCallback(Handler.java:615)
08-31 10:40:51.844: E/WindowManager(1239): at android.os.Handler.dispatchMessage(Handler.java:92)
08-31 10:40:51.844: E/WindowManager(1239): at android.os.Looper.loop(Looper.java:137)
08-31 10:40:51.844: E/WindowManager(1239): at android.app.ActivityThread.main(ActivityThread.java:4745)
08-31 10:40:51.844: E/WindowManager(1239): at java.lang.reflect.Method.invokeNative(Native Method)
08-31 10:40:51.844: E/WindowManager(1239): at java.lang.reflect.Method.invoke(Method.java:511)
08-31 10:40:51.844: E/WindowManager(1239): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
08-31 10:40:51.844: E/WindowManager(1239): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
08-31 10:40:51.844: E/WindowManager(1239): at dalvik.system.NativeStart.main(Native Method)


Thank you




In my android application am doing voice recording operation. Just am getting the path and storing as a String object. But when i try to save in the Sqlite, IT throws SqliteException : no such column. I tried to print the String and am getting this path - /storage/sdcard/rec_31_8_201462058.mp3. Can someone help me why i can't store this value in Sqlite. Thanks in advance.




I am working on SDK that you can add to your app. with every app i attach it i get logcat error : BLUETOOTH permission is missing!


My sdk doesn't require or doing anything that has any connection to bluetooth and i don't want to add this permission. Does someone have an idea why it happens?




At this point I have the following setup: A user scans a QR code, is redirected to a mobile site with a list of apps. Upon clicking on a link, the user is redirected to the app's AppStore page


QR code scan -> QR code scanner's browser loads page -> AppStore loaded


The problem is that onnce the Appstore is loaded, it is hard to return to the browser imbedded in the QR code scanner app. It is necessary to scan the QR code again in order to get to the app list again.


Is there a way to load the app list (mobile site) in the smartphone's default browser or in a way so it remains visible and accessible even after AppStore is loaded?




I wrote an application that use data from existing database on asset folder. for copy and use data I wrote following ExternalOpenDbHelper:



public class ExternalDbOpenHelper extends SQLiteOpenHelper {

public static String DB_PATH;

private static String TABALE_NAME = "font";
private static String FONT_ID = "_id";
private static String FONT_TYPE = "font_type";
private static String FONT_SIZE = "font_size";

private static String POEM_TABLE = "poem";
private static String POEM_ID = "_id";
private static String READ_POINT = "read_point";
private static String BOOKMARK = "bookmark";

public static String DB_NAME;
public SQLiteDatabase database;
public final Context context;
private static final int DATABASE_VERSION = 2;

public SQLiteDatabase getDb() {
return database;
}

public ExternalDbOpenHelper(Context context, String databaseName) {
super(context, databaseName, null, DATABASE_VERSION);
this.context = context;

String packageName = context.getPackageName();

DB_PATH = String.format("//data//data//%s//databases//", packageName);
DB_NAME = databaseName;
openDataBase();
}

public void createDataBase() {
boolean dbExist = checkDataBase();
if (!dbExist) {
this.getReadableDatabase();
try {
copyDataBase();
} catch (IOException e) {
Log.e(this.getClass().toString(), "Copying error");
throw new Error("Error copying database!");
}
} else {
Log.i(this.getClass().toString(), "Database already exists");
}
}

private boolean checkDataBase() {
SQLiteDatabase checkDb = null;
try {
String path = DB_PATH + DB_NAME;
checkDb = SQLiteDatabase.openDatabase(path, null,
SQLiteDatabase.OPEN_READONLY);
} catch (SQLException e) {
Log.e(this.getClass().toString(), "Error while checking db");
}
if (checkDb != null) {
checkDb.close();
}
return checkDb != null;
}

private void copyDataBase() throws IOException {

InputStream externalDbStream = context.getAssets().open(DB_NAME);

String outFileName = DB_PATH + DB_NAME;

OutputStream localDbStream = new FileOutputStream(outFileName);

byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = externalDbStream.read(buffer)) > 0) {
localDbStream.write(buffer, 0, bytesRead);
}
localDbStream.close();
externalDbStream.close();

}

public SQLiteDatabase openDataBase() throws SQLException {
String path = DB_PATH + DB_NAME;
if (database == null) {
createDataBase();
database = SQLiteDatabase.openDatabase(path, null,
SQLiteDatabase.OPEN_READWRITE);
}
return database;
}

@Override
public synchronized void close() {
if (database != null) {
database.close();
}
super.close();
}

@Override
public void onCreate(SQLiteDatabase db) {
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

if (newVersion > oldVersion) {
db.execSQL("ALTER TABLE cat ADD point BOOLEAN NOT NULL DEFAULT 0;");
db.execSQL("ALTER TABLE poem ADD read_point BOOLEAN NOT NULL DEFAULT false;");
db.execSQL("ALTER TABLE poem ADD bookmark INTEGER NOT NULL DEFAULT 0;");
}
}

public int updateFont(int i, String fontName, int p) {
SQLiteDatabase db = this.getWritableDatabase();

ContentValues font = new ContentValues();
font.put(FONT_TYPE, fontName);
font.put(FONT_SIZE, p);

String whereClause = FONT_ID + " LIKE ?";
String[] whereArgs = new String[] { String.valueOf(i) };

return db.update(TABALE_NAME, font, whereClause, whereArgs);
}

public void updateReadPoint(int poemId, int readPointTeransfer) {
SQLiteDatabase db = this.getWritableDatabase();
String whereClause;
String[] whereArgs;

if (poemId != readPointTeransfer) {
ContentValues readPoint = new ContentValues();
readPoint.put(READ_POINT, Boolean.toString(true));

whereClause = POEM_ID + " LIKE ?";
whereArgs = new String[] { String.valueOf(poemId) };

db.update(POEM_TABLE, readPoint, whereClause, whereArgs);

if (readPointTeransfer != -1) {
readPoint.put(READ_POINT, Boolean.toString(false));
whereArgs = new String[] { String.valueOf(readPointTeransfer) };
db.update(POEM_TABLE, readPoint, whereClause, whereArgs);
}
}
}

public void updateBookmarkList(int i, String idOfThisPoem) {


SQLiteDatabase db = this.getWritableDatabase();
ContentValues bookmarkValue = new ContentValues();
String whereClause = POEM_ID + " LIKE ?";
String[] whereArgs = new String[] { idOfThisPoem };
if (i == 0) {

bookmarkValue.put(BOOKMARK, Integer.toString(0));
db.update(POEM_TABLE, bookmarkValue, whereClause, whereArgs);
} else if (i == 1) {

bookmarkValue.put(BOOKMARK, Integer.toString(1));
db.update(POEM_TABLE, bookmarkValue, whereClause, whereArgs);
}
}

public boolean bookmarkStatus(String idOfThisPoem){
String idOfThisBookmarkedPoem = null;
Boolean iconFull = null;

String[] tableColumns = new String[] { POEM_ID, BOOKMARK };
String whereClause = POEM_ID + " LIKE ?";
String[] whereArgs = new String[] { idOfThisPoem };
Cursor poetCursor = database.query(POEM_TABLE, tableColumns,
whereClause, whereArgs, null, null, POEM_ID);

poetCursor.moveToFirst();
if (!poetCursor.isAfterLast()) {
do {

idOfThisBookmarkedPoem = poetCursor.getString(1);

} while (poetCursor.moveToNext());
}
poetCursor.close();

if (Integer.valueOf(idOfThisBookmarkedPoem) == 0) {
iconFull = false;

} else if (Integer.valueOf(idOfThisBookmarkedPoem) == 1) {
iconFull = true;

}
return iconFull;
}

}


In my code I checked if the data was copied on the phone don't copy again but if there wasn't on the path it copy from asset folder and read/write on the copied database on phone. I can't copy database from asset every time that app get run because I just write on the database that (//data//data//%s//databases//). Now I need to add new columns on two table of it and because I released it before don't like end user uninstall and install the app again. I try and googled lots of job but couldn't find solution. I guess if I could remove data on (//data//data//%s//databases//) path could do it right.




I try to set up a grid view like in this tutorial : http://developer.android.com/guide/topics/ui/layout/gridview.html


But I want a fragment and setContentView in a fragment is not working. What I have to change to make it works ?


Thanks.




08-31 10:28:41.806: E/SQLiteLog(2863): (1) table score has no column named _name 08-31 10:28:41.806: E/SQLiteDatabase(2863): Error inserting _name=yeni _score=555 08-31 10:28:41.806: E/SQLiteDatabase(2863): android.database.sqlite.SQLiteException: table score has no column named _name (code 1): , while compiling: INSERT INTO score(_name,_score) VALUES (?,?) 08-31 10:28:41.806: E/SQLiteDatabase(2863): at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method) 08-31 10:28:41.806: E/SQLiteDatabase(2863): at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:889) 08-31 10:28:41.806: E/SQLiteDatabase(2863): at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:500) 08-31 10:28:41.806: E/SQLiteDatabase(2863): at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588) 08-31 10:28:41.806: E/SQLiteDatabase(2863): at android.database.sqlite.SQLiteProgram.(SQLiteProgram.java:58) 08-31 10:28:41.806: E/SQLiteDatabase(2863): at android.database.sqlite.SQLiteStatement.(SQLiteStatement.java:31) 08-31 10:28:41.806: E/SQLiteDatabase(2863): at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1467) 08-31 10:28:41.806: E/SQLiteDatabase(2863): at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1339) 08-31 10:28:41.806: E/SQLiteDatabase(2863): at com.example.memoryofgame.DatabaseHandler.addScore(DatabaseHandler.java:63) 08-31 10:28:41.806: E/SQLiteDatabase(2863): at com.example.memoryofgame.GameActivity$1$1.run(GameActivity.java:498) 08-31 10:28:41.806: E/SQLiteDatabase(2863): at android.os.Handler.handleCallback(Handler.java:730) 08-31 10:28:41.806: E/SQLiteDatabase(2863): at android.os.Handler.dispatchMessage(Handler.java:92) 08-31 10:28:41.806: E/SQLiteDatabase(2863): at android.os.Looper.loop(Looper.java:137) 08-31 10:28:41.806: E/SQLiteDatabase(2863): at android.app.ActivityThread.main(ActivityThread.java:5103) 08-31 10:28:41.806: E/SQLiteDatabase(2863): at java.lang.reflect.Method.invokeNative(Native Method) 08-31 10:28:41.806: E/SQLiteDatabase(2863): at java.lang.reflect.Method.invoke(Method.java:525) 08-31 10:28:41.806: E/SQLiteDatabase(2863): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737) 08-31 10:28:41.806: E/SQLiteDatabase(2863): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553) 08-31 10:28:41.806: E/SQLiteDatabase(2863): at dalvik.system.NativeStart.main(Native Method)


public class Score {



private int id;
private String score;
private String date;

public Score(int id,String score,String date) {

this.id=id;
this.score=score;
this.date=date;
}

public Score(String score, String date) {
// TODO Auto-generated constructor stub
this.score=score;
this.date=date;

}

public Score() {
// TODO Auto-generated constructor stub
}

public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

public String getScore() {
return score;
}

public void setScore(String score) {
this.score = score;
}

public String getDate() {
return date;
}

public void setDate(String date) {
this.date = date;
}


}


public class DatabaseHandler extends SQLiteOpenHelper {



// All Static variables
// Database Version
private static final int DATABASE_VERSION = 1;

// Database Name
private static final String DATABASE_NAME = "game";

// Table name
private static final String TABLE_SCORE = "scores";

// Score Table Columns names
private static final String KEY_ID_SCORE = "_id";
private static final String KEY_SCORE = "_score";
private static final String KEY_DATE="_date";

public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

// Creating Tables
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_SCORE + "("
+ KEY_ID_SCORE+" INTEGER PRIMARY KEY AUTOINCREMENT, "
+ KEY_SCORE + " TEXT NOT NULL, "
+ KEY_DATE + "TEXT NOT NULL);");

}

// Upgrading database
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_SCORE);

// Create tables again
onCreate(db);
}

// Adding new score
public void addScore(Score score) {

Log.d("addScore", score.toString());
SQLiteDatabase db = this.getWritableDatabase();

ContentValues values = new ContentValues();
values.put(KEY_SCORE, score.getScore());
values.put(KEY_DATE, score.getDate());// score value

// Inserting Values
db.insert(TABLE_SCORE, null, values);
db.close();

}

//Getting single score

public Score getScore(int id){

SQLiteDatabase db=this.getReadableDatabase();
Cursor cursor=db.query(TABLE_SCORE, new String[]{KEY_ID_SCORE,KEY_SCORE,KEY_DATE},KEY_ID_SCORE+"=?",new String[] {String.valueOf(id)}, null, null, null);

if(cursor!=null){
cursor.moveToFirst();
}
Score score=new Score(Integer.parseInt(cursor.getString(0)), cursor.getString(1), cursor.getString(2));
return score;
}

// Getting All Scores
public List<Score> getAllScores() {

List<Score> scoreList=new ArrayList<Score>();

// Select All Query
String selectQuery = "SELECT *FROM " + TABLE_SCORE;

SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);

// looping through all rows and adding to list

if(cursor.moveToFirst()&& cursor!=null && cursor.getCount() > 0){
while(cursor.moveToNext())
{
Score score=new Score();
score.setId(Integer.parseInt(cursor.getString(0)));
score.setScore(cursor.getString(1));
score.setDate(cursor.getString(2));
//Adding score to list
scoreList.add(score);

};
}
cursor.close();
db.close();
return scoreList;
}

//Deleting single score
public void deleteScore(Score score){
SQLiteDatabase db=this.getWritableDatabase();
db.delete(TABLE_SCORE, KEY_ID_SCORE+"=?",new String[] {String.valueOf(score.getId())});
db.close();
}


}


public class ScoreTable extends Activity{



private DatabaseHandler db;

private TextView tvScoreTable;

protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.score_table);

db=new DatabaseHandler(this);
tvScoreTable=(TextView) findViewById(R.id.tvScoreTable);
tvScoreTable.setOnClickListener(new View.OnClickListener()
{

@Override
public void onClick(View v)
{

// Reading all contacts
Log.d("Reading: ", "Reading all contacts..");
List<Score> score = db.getAllScores();

for (Score cn : score)
{
String log="Id: "+cn.getId()+" ,Score: " + cn.getScore() + " ,Date: " + cn.getDate();
// Writing Contacts to log
Log.d("Name: ", log);
}
}
});


}


}




I'm using the last Kikat API to acess to the user notification and get some data. Currently I use this code:



@Override
public void onNotificationPosted(StatusBarNotification arg0) {
String originator = arg0.getPackageName();
Bundle extras = arg0.getNotification().extras;
if (extras != null) {
String title = extras.getString(Notification.EXTRA_TITLE);
String subText = extras.getString(Notification.EXTRA_SUB_TEXT);
String text = extras.getString(Notification.EXTRA_TEXT);
CharSequence ticker = arg0.getNotification().tickerText;
//do something
}
}


This code doesn't work with multiple messages of WhatsApp. Unfortunately I don't use this app so I don't know what fields uses. Can someone give me some information? Can someone share a dumpsys notificationADB command output?




I have one question if it is possible to development android game with unity free. And if i can add adwartismant in game? Thanks for answer




Why in Android one should use openFileOutput() method instead of FileOutputStream() constructor?


Would the mode type as a second param of openFileOutput() be the only "respectful" reason for all the cases?



FileOutputStream fos;
fos = openFileOutput("test.txt", Context.MODE_PRIVATE);
fos = new FileOutputStream("test.txt");



Hi I wrote a program with Google Maps API V2 . this program run on emulator But when run on real devices I see only white screen whit Google logo and Zoom buttons . What is the problem ? my phone is Samsung galaxy s2. thanks ;)




i want to remove the signed below line from the action bar, how i can do that?


this is my action bar:


enter image description here


this is my menu.xml file:



<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
>

<item
android:id="@+id/foo2"
android:icon="@drawable/foo2"
android:showAsAction="ifRoom|withText"
android:title="@string/foo2"/>
<item
android:id="@+id/foo"
android:orderInCategory="100"
android:showAsAction="always"
android:title="@string/foo"/>
<item
android:id="@+id/foo1"
android:icon="@drawable/foo1"
android:showAsAction="ifRoom|withText"
android:title="@string/foo1"/>

</menu>


thanks in advance




here is the code that i find does it help me? AnimatorSet bouncer = new AnimatorSet(); bouncer.play(bounceAnim).before(squashAnim1); bouncer.play(squashAnim1).with(squashAnim2); bouncer.play(squashAnim1).with(stretchAnim1); bouncer.play(squashAnim1).with(stretchAnim2); bouncer.play(bounceBackAnim).after(stretchAnim2); ValueAnimator fadeAnim = ObjectAnimator.ofFloat(newBall, "alpha", 1f, 0f); fadeAnim.setDuration(250); AnimatorSet animatorSet = new AnimatorSet(); animatorSet.play(bouncer).before(fadeAnim); animatorSet.start();




all I am doing:


Exlipse --> new Project --> Android Application --> Activity type: blank


no changes in the code, just the simple Hello world.


It does start, I see the Hello World on the virtual device, but then immediatly shuts down.


The logcat is as follows:



08-31 06:01:14.976: W/dalvikvm(1114): threadid=1: thread exiting with uncaught exception(group=0xb2aeeba8)
08-31 06:01:14.996: E/AndroidRuntime(1114): FATAL EXCEPTION: main
08-31 06:01:14.996: E/AndroidRuntime(1114): Process: com.example.tester, PID: 1114
08-31 06:01:14.996: E/AndroidRuntime(1114): java.lang.NoClassDefFoundError: android.support.v7.appcompat.R$styleable
08-31 06:01:14.996: E/AndroidRuntime(1114): at android.support.v7.app.ActionBarActivityDelegate.onCreate(ActionBarActivityDelegate.java:107)


Any Ideas?




i have a library to insert floating buttons in a layout (http://prolificinteractive.com/blog/2014/07/24/android-floating-action-button-aka-fab/)


Then, i have this layout:



<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:fontawesometext="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">

<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="16dp"
android:layout_marginTop="32dp"
android:layout_marginBottom="16dp"
android:layout_marginRight="16dp">

<com.beardedhen.androidbootstrap.FontAwesomeText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:layout_marginLeft="16dp"
android:layout_marginRight="4dp"
android:textSize="45sp"
android:textColor="#737373"
android:id="@+id/faIcon"
fontawesometext:fa_icon="fa-question" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text='"texto de ejemplo de pregunta"'
android:id="@+id/tvQuestion"
android:textColor="@color/primary"
android:textStyle="bold"
android:textSize="28sp"
android:typeface="monospace"
android:layout_marginLeft="16dp"
android:layout_marginTop="32dp"
android:layout_marginBottom="16sp" />
</LinearLayout>

<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/frameConainter"
android:background="@color/dark_grey" />

</LinearLayout>


And i need to set the center of the button in the middle of framelayout top, like as the left image:


http://tabtec.com/wp-content/uploads/2014/06/andl3.jpg


I have this in a custom view:



public class YesNoReplyView extends ReplyParentView {

private FloatingActionButton buttonYes;
private FloatingActionButton buttonNo;

public YesNoReplyView(Context context) {
super(context);
}

public YesNoReplyView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}

@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public YesNoReplyView(Context context, AttributeSet attrs) {
super(context, attrs);
}

@Override
public void initializeComponents() {

int[] position = new int[2];
getLocationOnScreen(position);

buttonYes = new FloatingActionButton.Builder((Activity)getContext())
.withDrawable(getResources().getDrawable(R.drawable.ic_plus))
.withButtonColor(getResources().getColor(R.color.green_success))
.withGravity(Gravity.BOTTOM | Gravity.RIGHT)
.withMargins(0, 0, 16, 16)
.create();

buttonNo = new FloatingActionButton.Builder((Activity)getContext())
.withDrawable(getResources().getDrawable(R.drawable.ic_plus))
.withButtonColor(getResources().getColor(R.color.primary))
.withGravity(Gravity.BOTTOM | Gravity.RIGHT)
.withMargins(0, 0, 26, 26)
.create();

}


@Override
public String getResult() {
String result = "";
return result;
}
}


But i dont know how can i calculate the margins from the coordinates to set the view in the position i want..


Anyone knows any way better to do it this?(I cant use a XML layout..)




I want to copy zip file that includes images from asset to internal storage,And then unzip it. This is my code :



protected void copyFromAssetsToInternalStorage(String filename){
AssetManager assetManager = getAssets();

try {
InputStream input = assetManager.open(filename);
OutputStream output = openFileOutput(filename, Context.MODE_PRIVATE);

copyFile(input, output);

} catch (IOException e) {
e.printStackTrace();
}
}

private void unZipFile(String filename){
try {
ZipInputStream zipInputStream = new ZipInputStream(openFileInput(filename));
ZipEntry zipEntry;

while((zipEntry = zipInputStream.getNextEntry()) != null){
FileOutputStream zipOutputStream = openFileOutput(zipEntry.getName(), MODE_PRIVATE);

int length;
byte[] buffer = new byte[1024];

while((length = zipInputStream.read(buffer)) > 0){
zipOutputStream.write(buffer, 0, length);
}

zipOutputStream.close();
zipInputStream.closeEntry();
}
zipInputStream.close();

} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

private void copyFile(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[1024];
int read;
while((read = in.read(buffer)) != -1){
out.write(buffer, 0, read);
}
}


And i have this error : java.lang.IllegalArgumentException: File filename/ contains a path separator


What should i do?




I have implemented inapp purchasing in my application. When I buy a managed application it shows me this error log. Can anyone tell me why this happen?


Here is my logcat:



08-31 14:58:00.931: E/IABUtil/Security(31515): Purchase verification failed: missing data.
08-31 14:58:00.931: E/viable(31515): Public key signature doesn't match!


and here is my Security.java Class



/* Copyright (c) 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package Classes;

import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;

import java.security.InvalidKeyException;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;
import java.security.Signature;
import java.security.SignatureException;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.X509EncodedKeySpec;

/**
* Security-related methods. For a secure implementation, all of this code
* should be implemented on a server that communicates with the
* application on the device. For the sake of simplicity and clarity of this
* example, this code is included here and is executed on the device. If you
* must verify the purchases on the phone, you should obfuscate this code to
* make it harder for an attacker to replace the code with stubs that treat all
* purchases as verified.
*/
class Security {
private static final String TAG = "IABUtil/Security";

private static final String KEY_FACTORY_ALGORITHM = "RSA";
private static final String SIGNATURE_ALGORITHM = "SHA1withRSA";


/**
* Verifies that the data was signed with the given signature, and returns
* the verified purchase. The data is in JSON format and signed
* with a private key. The data also contains the {@link PurchaseState}
* and product ID of the purchase.
* @param base64PublicKey the base64-encoded public key to use for verifying.
* @param signedData the signed JSON string (signed, not encrypted)
* @param signature the signature for the data, signed with the private key
*/
public static boolean verifyPurchase(String base64PublicKey, String signedData, String signature) {
if (TextUtils.isEmpty(signedData) || TextUtils.isEmpty(base64PublicKey) ||
TextUtils.isEmpty(signature)) {
Log.e(TAG, "Purchase verification failed: missing data.");
return false;
}

PublicKey key = Security.generatePublicKey(base64PublicKey);
return Security.verify(key, signedData, signature);
}

/**
* Generates a PublicKey instance from a string containing the
* Base64-encoded public key.
*
* @param encodedPublicKey Base64-encoded public key
* @throws IllegalArgumentException if encodedPublicKey is invalid
*/
public static PublicKey generatePublicKey(String encodedPublicKey) {
try {
byte[] decodedKey = Base64.decode(encodedPublicKey, Base64.DEFAULT);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_FACTORY_ALGORITHM);
return keyFactory.generatePublic(new X509EncodedKeySpec(decodedKey));
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
} catch (InvalidKeySpecException e) {
Log.e(TAG, "Invalid key specification.");
throw new IllegalArgumentException(e);
} catch (IllegalArgumentException e) {
Log.e(TAG, "Base64 decoding failed.");
throw e;
}
}

/**
* Verifies that the signature from the server matches the computed
* signature on the data. Returns true if the data is correctly signed.
*
* @param publicKey public key associated with the developer account
* @param signedData signed data from server
* @param signature server signature
* @return true if the data and signature match
*/
public static boolean verify(PublicKey publicKey, String signedData, String signature) {
Signature sig;
try {
sig = Signature.getInstance(SIGNATURE_ALGORITHM);
sig.initVerify(publicKey);
sig.update(signedData.getBytes());
if (!sig.verify(Base64.decode(signature, Base64.DEFAULT))) {
Log.e(TAG, "Signature verification failed.");
return false;
}
return true;
} catch (NoSuchAlgorithmException e) {
Log.e(TAG, "NoSuchAlgorithmException.");
} catch (InvalidKeyException e) {
Log.e(TAG, "Invalid key specification.");
} catch (SignatureException e) {
Log.e(TAG, "Signature exception.");
} catch (IllegalArgumentException e) {
Log.e(TAG, "Base64 decoding failed.");
}
return false;
}
}



I have a progress bar and a textview


My progressbar.xml looks like



<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:innerRadiusRatio="3"
android:shape="ring"
android:thicknessRatio="7.0">
<gradient
android:centerColor="#007DD6"
android:endColor="#FF000F"
android:startColor="#007DD6"
android:angle="90"
android:type="sweep"
android:useLevel="false" />
</shape>


My layout is:



<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center">
<ProgressBar
android:id="@+id/progressBar"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="60dp"
android:layout_height="60dp"
android:indeterminate="false"
android:max="60"
android:progressDrawable="@drawable/progressbar">
</ProgressBar>
<TextView
android:id="@+id/progresstext"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:background="@android:color/transparent"
android:gravity="center" />
</RelativeLayout>

one more frame layout after this


I have a countdown of 60 seconds and i show that in progresstext. What i want to do is whenever the count down reaches 45 seconds, i want to change the color of inner circle to red(or any color for that matter) to indicate the user about the time.


I have tried changing the background color of textview but it did not cover the whole inner circle. Is there any way to change the color of the inner circle???


Thank you :)




Is it possible to create video of series of Images present on SdCard using MediaCodec? if yes, can anyone share me the link? I want to import images from sdcard and crete video from those images, any suggestions???




I've just started learning javascript and java programming. I'm learning on codecademy and on udemy. I wanted to start building a simple show battery percentage app on Android as my 1st project. Can you please guide me?




I was browsing through the net about SharedPreferences and I came across something that I've never seen in a SharedPreferences statement.


I wonder if anyone could explain to me what this means:



Editor editor = sPrefs.edit();
if(editText1CheckBox.isChecked){
editor.putBoolean("STRING_NAME"+(a+100)+(b+100), false);
}else {
editor.putBoolean("STRING_NAME"+(a+100)+(b+100), true);
}


So I would appreciate if anyone could explain to mean what does the (a+100) and (b+100) means? What if it was a different variable/number? What does it mean?


Thanks.




I'm working on an application and managing its repo on bitbucket.


During the development process, I created a new branch 'price-module' a few days ago and pushed its changes in the remote branch by the same name. Now, when I'm merging 'price-module' to 'development' branch, bitbucket is showing me an error that there are conflicts between these files. (specifically in bin/R.txt). How can I resolve these conflicts and merge the changes I did in 'price-module' to 'development' branch without losing my code?


PS: the project I'm working on is an Android project.




Hey i'm new to OpenGL i'm using the opengl ES 2.0 Example in the android developers site.


I'm getting the screen cordinates of using the touch events in android.


public boolean onTouchEvent(MotionEvent e) {



float x = e.getX();
float y = e.getY();


}


can anyone please help me in converting them into opneGL world coordinates.


thanks in Advance




new to Android there is something i really do to understand with bitmap.


I use a custom camera which i open on a Handler thread to take photo on my jpeg callback i want to store my picture in cache after scaling down the picture so the pictures fits in a 1000 x 1000 size keeping its ratio.


To do so i take the picture from the jpeg callback using :



private Camera.PictureCallback jpegCallback = new Camera.PictureCallback() {
public void onPictureTaken(byte[] data, final Camera camera) {

Bitmap realImage;
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 4;
options.inPurgeable=true;
options.inInputShareable=true;
realImage = BitmapFactory.decodeByteArray(data,0,data.length,options);


So far so good, i can take as many pictures as i want, no memory problem...


But when i want to write the picture to cache i need to scaled it down using :



private class addThumbnailASYNC extends AsyncTask<Bitmap, Void, Bitmap> {
@Override
protected Bitmap doInBackground(Bitmap... bitmap) {

Bitmap image = bitmap[0];
int width = image.getWidth();
int height = image.getHeight();

float bitmapRatio = (float)width / (float) height;
if (bitmapRatio > 0) {
width = MAX_SIZE_IMAGE;
height = (int) (width / bitmapRatio);
} else {
height = MAX_SIZE_IMAGE;
width = (int) (height * bitmapRatio);
}

image = Bitmap.createScaledBitmap(image, width, height, true);


the problem is when i use image = Bitmap.createScaledBitmap I get a Grow heap which i think will lead to an out of memory if i take many picture.


There are 3 things that i do understand : - When i use options.inSampleSize the picture should be scaled by 4 so why createScaledBitmap causes a grow heap ? - If i do not use createScaledBitmap and that i write the image to cache i never get the grow heap why ? The inSampleSize should gave me more heavy file than the one i create using scaledBitmap ? - I need to avoid memory heap, but how to avoid grow heap because i have no choice using createdScaledBitmap and my picture will be always taken by the camera, i feel stuck.


Thank you for any help, any clues or more ...




Every Android app you'll create will be signed, and you will need to register each app's key hash with Facebook as a security check for authenticity.


keytool -exportcert -alias androiddebugkey -keystore "C:\Users\DELL.android\debug.keystore" | "C:\OpenSSL\bin\openssl" sha1 -binary |"C:\OpenSSL\bin\openssl" base64


I generated hashkey through above command and updated in Facebook developer account.


SO, whenever my app is doing request to facebook, will this hashkey will be generated dynamically through Facebook SDK and will it be checked against the hashkey stored in Facebook dveoper page.




I'm trying to find the REAL Camera max Megapixels of a device and i tested some code found on stackoverflow and google with cam.getParameters().getSupportedPictureSizes();, but the code does not work well on all the devices.


For example on NEXUS 5 it works fine and tells that the device haves 8Mpx, but in BQ Aquaris E5 FHD with KitKat 4.4.2 it does not work well and tells that the device haves 19 Mpx (it haves 13 Mpx...)


The problem in Bq Aquaris is that the code obtains all the supported picture sizes, and the most huge value is 5888x3312, that value means 19.5 mpx, but really this device does not support 19.5 mpx, so i dont understand why 5888x3312 is returend by getSupportedPictureSizes() and i dont know how i must ignore non real values like that value.


This is the code that does not work properly:



DecimalFormat localDecimalFormat = new DecimalFormat("#.#", symbols);
String sizeInMegapixel=getString(R.string.not_available);
if(cam!=null){
Camera.Parameters camParams=cam.getParameters();
List<Size> list = cam.getParameters().getSupportedPictureSizes();
Camera.Size size;
Size maxSize=list.get(0);
int aux;
int maxAux=0;

for (int i=0;i<list.size();i++){
size=list.get(i);
aux = size.width*size.height;
if (aux>maxAux){
maxAux=aux;
maxSize=size;
}
}
sizeInMegapixel=localDecimalFormat.format((maxSize.width*maxSize.height)/1000000.0D);
}



when my connection is alive at Active Mq and just in case if my 3G network link goes down in my mobile app and then i try to reconnect on the same connection string , i am not be able to connect and i can see a live connection in Active MQ. my app only get a chance to reconnect once that session at server get destroyed automatically and then it takes lot of time in reconnecting.


i have used session clean to false and QoS to 1 now is there anything to set so that i can reconnect immediately.


so is there a way to reconnect to server immediately ?


enter image description here




I have built a website in spring mvc framework. I want to deploy it to an android app using cordova. For that purpose I installed cordova and required plugins (contact plugin in this case). I took all the js files of cordova and put it on the server. I am including these files in a html file from the server.


Whenever any communication from Js to Native takes place it uses prompt function. Android function onJsPrompt is called whenever prompt function is invoked in javascript. Cordova overrides this android function to intercept messages from Js.


Now my problem is, if I am installing application on phone then it works fine. But if I load cordova.js from server it pops up user prompt and native side doesn't intercept. And hence, no js-native communication takes place.




I have a bunch of crude graphic objects and I want to draw them efficiently (meaning with a good ratio of fast and without much memory overhead). Think of something like "draw 4 circle next to each other" and even with a bit more logic like "draw as much circles as fit in this space". The kicker is: There are hundreds of different drawing instructions, but only a dozens or so are effectively used at once.


As a programmer, that screams for an interface, where the implementations do the actual drawing, but that also means having hundreds of classes, which after their first use will not get garbage collected. Also there might be a lot of duplicated code and big maps of some kind that hold strings and classes to be initialized.


Another option might be XML files, which Android can handle well. Maybe even SVG files, but for the logic I need I will probably need my own format as well. These files might need a bit of time and memory to get loaded, but unused components can be garbage collected well. This approach would also need some kind of registry to register all these files, and skipping through them would be very slow (but this is hardly ever needed, if at all).


I don't think that is an unusual request (having a lot of potential information where only a small percentage is used at a time), so I want to know: Is there another way I'm missing? What is the correct way to approach this problem? What are the professionals doing?




I am using TabHost along with ViewPager in my app. In first tab fragment there are few buttons in second tab fragment I have a map(with clusterkarf).


I use to develop on S3 and nexus5 where everything works fine, But when I tested on Experia U(http://www.gsmarena.com/sony_xperia_u-4437.php) TabHost thing breaks.


Detail description of issue:


->First Tab is always rendered properly, but when I go to second tab and come back to first tab things break.


->Black screen is shown with some part of fragment underneath it (Black screen is exactly same size of map fragment with empty spaces where zoom button are.). Seems as if android tried but was unable to display whole thing.


My only hunch is that there might be some issue with low memory devices, Since maps and clusterkarf might take a lot of memory the previous fragment might have been swapped out.




Is there a way to get the contact-list of my samsung galaxy s3 via adb-command.


I tried with the following but got a "permission-denied" error in windows-cmd.



failed to copy '/data/data/com.android.providers.contacts/databases/contacts2.db
' to './contacts2.db': Permission denied


Thanks in advance!




I add these lines to the default Clock Widget in Android - AIDE



android:dial="@drawable/dial"

android:hand_hour="@drawable/hour"

android:hand_minute="@drawable/minute"/>


But in Output of Analog Clock all things are o.k except the HOUR HAND and MINUTE HAND Can anybody tell me that how to fix this issue? The hour and minute hand cross each other they are not in radius ?




What is the native Android way to implement long running network operations (like uploading a bunch of photos) without having to use libraries like RoboSpice?


How do I replace my asynctask with something else?


Now, I've heard of handlers, executors, services and what not, but how exactly do I implement them in my code and which one to choose?


Here is an example of the asynctask I use


I have removed a lot of code, just so you can see the basic structure



public class UploadPhotosToServer extends AsyncTask<String, Void, Boolean> {

@Override
protected Boolean doInBackground(String... args) {

HashMap<String, String> params = new HashMap<String, String>();


try {
if(uploadImageToServer(id, path, params)) {
success = true;
} else {
success = false;
}
} catch (Exception e) {
e.printStackTrace();
success = false;
}


return success;
}

public boolean uploadImageToServer(int imageId, String imagePath, HashMap<String, String> params) throws Exception {

try {
JSONObject json = jsonParser.uploadImageToServer(imagePath, params);
JSONObject message = json.getJSONObject("message");
String serverResponse = message.getString("success");
if (serverResponse.contentEquals("true") {
return true;
} else {
return false;
}
} catch (JSONException e) {
e.printStackTrace();
return false;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}

}


and here is jsonParser.uploadImageToServer



public JSONObject uploadImageToServer(String imagePath, HashMap<String, String> params) throws Exception {
HttpClient httpClient;
HttpResponse response;
MultipartEntityBuilder multipartEntity;
HttpPost postRequest;
HttpContext localContext;
Bitmap bitmap;

try {
// Set the http handlers
httpClient = new DefaultHttpClient();
localContext = new BasicHttpContext();
postRequest = new HttpPost(API.IMAGES);
// Deal with the file
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bitmap = BitmapFactory.decodeFile(imagePath);
bitmap.compress(CompressFormat.JPEG, 100, byteArrayOutputStream);
bitmap.recycle();
// Second parameter is the image quality in per cent. The bitmap converts into the third parameter that we later
// use.
byte[] byteData = byteArrayOutputStream.toByteArray();
ByteArrayBody byteArrayBody = new ByteArrayBody(byteData, "temp_image"); // second parameter is the name of the
// image
// Send the package
multipartEntity = MultipartEntityBuilder.create();
multipartEntity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
multipartEntity.addPart("file", byteArrayBody);
for (Map.Entry<String, String> entry : params.entrySet()) {
multipartEntity.addTextBody(entry.getKey(), entry.getValue());
}
postRequest.setEntity(multipartEntity.build());
// Get the response. we will deal with it in onPostExecute.
response = httpClient.execute(postRequest, localContext);
HttpEntity httpEntity = response.getEntity();
inputStream = httpEntity.getContent();
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
json = sb.toString();
inputStream.close();
reader.close();
} catch (ClientProtocolException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
httpClient.getConnectionManager().shutdown();
// Try parsing the string to a JSON object
try {
jsonObject = new JSONObject(json);
} catch (JSONException e) {
e.printStackTrace();
}
// Return JSON String
return jsonObject;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}



I recently started to work with achartengine. I would like to draw a simple linear graph but with offset away from the origin of the axis - (0,0). I changed the x array from the original values to start from 5.


This is my code so far



public class MainActivity extends Activity {

private String[] mMonth = new String[] {
"Jan", "Feb" , "Mar", "Apr", "May", "Jun",
};

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
openChart();
}
private void openChart(){
int[] x = { 5,6,7,8,9};
int[] income = { 240,467,259,570,500};
int[] expense = {200, 521, 290, 219, 457};

// Creating an XYSeries for Income
XYSeries incomeSeries = new XYSeries("Income");
// Creating an XYSeries for Income
XYSeries expenseSeries = new XYSeries("Expenses");
// Adding data to Income and Expense Series
for(int i=0;i<x.length;i++){
incomeSeries.add(x[i], income[i]);
expenseSeries.add(x[i],expense[i]);
}

// Creating a dataset to hold each series
XYMultipleSeriesDataset dataset = new XYMultipleSeriesDataset();
// Adding Income Series to the dataset
dataset.addSeries(incomeSeries);
// Adding Expense Series to dataset
dataset.addSeries(expenseSeries);


// Creating XYSeriesRenderer to customize incomeSeries
XYSeriesRenderer incomeRenderer = new XYSeriesRenderer();
incomeRenderer.setColor(Color.WHITE);
incomeRenderer.setPointStyle(PointStyle.CIRCLE);
incomeRenderer.setFillPoints(true);
incomeRenderer.setLineWidth(2);
incomeRenderer.setDisplayChartValues(true);

// Creating XYSeriesRenderer to customize expenseSeries
XYSeriesRenderer expenseRenderer = new XYSeriesRenderer();
expenseRenderer.setColor(Color.BLUE);
expenseRenderer.setPointStyle(PointStyle.CIRCLE);
expenseRenderer.setFillPoints(true);
expenseRenderer.setLineWidth(3);
expenseRenderer.setDisplayChartValues(true);


// Creating a XYMultipleSeriesRenderer to customize the whole chart
XYMultipleSeriesRenderer multiRenderer = new XYMultipleSeriesRenderer();
multiRenderer.setXLabels(0);
multiRenderer.setChartTitle("Income vs Expense Chart");
multiRenderer.setXTitle("Year 2011");
multiRenderer.setYTitle("Amount in Rupees");
multiRenderer.setZoomButtonsVisible(true);
for(int i=0;i<x.length;i++){
multiRenderer.addXTextLabel(i+1, mMonth[i]);
}

// Adding incomeRenderer and expenseRenderer to multipleRenderer
// Note: The order of adding dataseries to dataset and renderers to multipleRenderer
// should be same
multiRenderer.addSeriesRenderer(incomeRenderer);
multiRenderer.addSeriesRenderer(expenseRenderer);

// Creating an intent to plot line chart using dataset and multipleRenderer
Intent intent = ChartFactory.getLineChartIntent(getBaseContext(), dataset, multiRenderer);

// Start Activity
startActivity(intent);

}


}


Thanks for your help




i want to make my own object of tracker like in Image Target example i want to replace the Teapot by another 3D shape , the problem is i can't understand the code very well! here is the Code: Teapot Class: have two Functions: setVerts() and setIndices() with alot of indices and vertices numbers


and the ImageTargetRender is:



// The renderer class for the ImageTargets sample.
public class ImageTargetRenderer implements GLSurfaceView.Renderer
{
private static final String LOGTAG = "ImageTargetRenderer";

private SampleApplicationSession vuforiaAppSession;
private ImageTargets mActivity;

private Vector<Texture> mTextures;

private int shaderProgramID;

private int vertexHandle;

private int normalHandle;

private int textureCoordHandle;

private int mvpMatrixHandle;

private int texSampler2DHandle;

private Teapot mTeapot;

private float kBuildingScale = 12.0f;
private SampleApplication3DModel mBuildingsModel;

private Renderer mRenderer;

boolean mIsActive = false;

private static final float OBJECT_SCALE_FLOAT = 3.0f;


public ImageTargetRenderer(ImageTargets activity,
SampleApplicationSession session)
{
mActivity = activity;
vuforiaAppSession = session;
}


// Called to draw the current frame.
@Override
public void onDrawFrame(GL10 gl)
{
if (!mIsActive)
return;

// Call our function to render content
renderFrame();
}


// Called when the surface is created or recreated.
@Override
public void onSurfaceCreated(GL10 gl, EGLConfig config)
{
Log.d(LOGTAG, "GLRenderer.onSurfaceCreated");

initRendering();

// Call Vuforia function to (re)initialize rendering after first use
// or after OpenGL ES context was lost (e.g. after onPause/onResume):
vuforiaAppSession.onSurfaceCreated();
}


// Called when the surface changed size.
@Override
public void onSurfaceChanged(GL10 gl, int width, int height)
{
Log.d(LOGTAG, "GLRenderer.onSurfaceChanged");

// Call Vuforia function to handle render surface size changes:
vuforiaAppSession.onSurfaceChanged(width, height);
}


// Function for initializing the renderer.
private void initRendering()
{
mTeapot = new Teapot();

mRenderer = Renderer.getInstance();

GLES20.glClearColor(0.0f, 0.0f, 0.0f, Vuforia.requiresAlpha() ? 0.0f
: 1.0f);

for (Texture t : mTextures)
{
GLES20.glGenTextures(1, t.mTextureID, 0);
GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, t.mTextureID[0]);
GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D,
GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_LINEAR);
GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D,
GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_LINEAR);
GLES20.glTexImage2D(GLES20.GL_TEXTURE_2D, 0, GLES20.GL_RGBA,
t.mWidth, t.mHeight, 0, GLES20.GL_RGBA,
GLES20.GL_UNSIGNED_BYTE, t.mData);
}

shaderProgramID = SampleUtils.createProgramFromShaderSrc(
CubeShaders.CUBE_MESH_VERTEX_SHADER,
CubeShaders.CUBE_MESH_FRAGMENT_SHADER);

vertexHandle = GLES20.glGetAttribLocation(shaderProgramID,
"vertexPosition");
normalHandle = GLES20.glGetAttribLocation(shaderProgramID,
"vertexNormal");
textureCoordHandle = GLES20.glGetAttribLocation(shaderProgramID,
"vertexTexCoord");
mvpMatrixHandle = GLES20.glGetUniformLocation(shaderProgramID,
"modelViewProjectionMatrix");
texSampler2DHandle = GLES20.glGetUniformLocation(shaderProgramID,
"texSampler2D");

try
{
mBuildingsModel = new SampleApplication3DModel();
mBuildingsModel.loadModel(mActivity.getResources().getAssets(),
"ImageTargets/Buildings.txt");
} catch (IOException e)
{
Log.e(LOGTAG, "Unable to load buildings");
}

// Hide the Loading Dialog
mActivity.loadingDialogHandler
.sendEmptyMessage(LoadingDialogHandler.HIDE_LOADING_DIALOG);

}


// The render function.
private void renderFrame()
{
GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT | GLES20.GL_DEPTH_BUFFER_BIT);

State state = mRenderer.begin();
mRenderer.drawVideoBackground();

GLES20.glEnable(GLES20.GL_DEPTH_TEST);

// handle face culling, we need to detect if we are using reflection
// to determine the direction of the culling
GLES20.glEnable(GLES20.GL_CULL_FACE);
GLES20.glCullFace(GLES20.GL_BACK);
if (Renderer.getInstance().getVideoBackgroundConfig().getReflection() == VIDEO_BACKGROUND_REFLECTION.VIDEO_BACKGROUND_REFLECTION_ON)
GLES20.glFrontFace(GLES20.GL_CW); // Front camera
else
GLES20.glFrontFace(GLES20.GL_CCW); // Back camera

// did we find any trackables this frame?
for (int tIdx = 0; tIdx < state.getNumTrackableResults(); tIdx++)
{
TrackableResult result = state.getTrackableResult(tIdx);
Trackable trackable = result.getTrackable();
printUserData(trackable);
Matrix44F modelViewMatrix_Vuforia = Tool
.convertPose2GLMatrix(result.getPose());
float[] modelViewMatrix = modelViewMatrix_Vuforia.getData();

int textureIndex = trackable.getName().equalsIgnoreCase("stones") ? 0
: 1;
textureIndex = trackable.getName().equalsIgnoreCase("tarmac") ? 2
: textureIndex;

// deal with the modelview and projection matrices
float[] modelViewProjection = new float[16];

if (!mActivity.isExtendedTrackingActive())
{
Matrix.translateM(modelViewMatrix, 0, 0.0f, 0.0f,
OBJECT_SCALE_FLOAT);
Matrix.scaleM(modelViewMatrix, 0, OBJECT_SCALE_FLOAT,
OBJECT_SCALE_FLOAT, OBJECT_SCALE_FLOAT);
} else
{
Matrix.rotateM(modelViewMatrix, 0, 90.0f, 1.0f, 0, 0);
Matrix.scaleM(modelViewMatrix, 0, kBuildingScale,
kBuildingScale, kBuildingScale);
}

Matrix.multiplyMM(modelViewProjection, 0, vuforiaAppSession
.getProjectionMatrix().getData(), 0, modelViewMatrix, 0);

// activate the shader program and bind the vertex/normal/tex coords
GLES20.glUseProgram(shaderProgramID);

if (!mActivity.isExtendedTrackingActive())
{
GLES20.glVertexAttribPointer(vertexHandle, 3, GLES20.GL_FLOAT,
false, 0, mTeapot.getVertices());
GLES20.glVertexAttribPointer(normalHandle, 3, GLES20.GL_FLOAT,
false, 0, mTeapot.getNormals());
GLES20.glVertexAttribPointer(textureCoordHandle, 2,
GLES20.GL_FLOAT, false, 0, mTeapot.getTexCoords());

GLES20.glEnableVertexAttribArray(vertexHandle);
GLES20.glEnableVertexAttribArray(normalHandle);
GLES20.glEnableVertexAttribArray(textureCoordHandle);

// activate texture 0, bind it, and pass to shader
GLES20.glActiveTexture(GLES20.GL_TEXTURE0);
GLES20.glBindTexture(GLES20.GL_TEXTURE_2D,
mTextures.get(textureIndex).mTextureID[0]);
GLES20.glUniform1i(texSampler2DHandle, 0);

// pass the model view matrix to the shader
GLES20.glUniformMatrix4fv(mvpMatrixHandle, 1, false,
modelViewProjection, 0);

// finally draw the teapot
GLES20.glDrawElements(GLES20.GL_TRIANGLES,
mTeapot.getNumObjectIndex(), GLES20.GL_UNSIGNED_SHORT,
mTeapot.getIndices());

// disable the enabled arrays
GLES20.glDisableVertexAttribArray(vertexHandle);
GLES20.glDisableVertexAttribArray(normalHandle);
GLES20.glDisableVertexAttribArray(textureCoordHandle);
} else
{
GLES20.glDisable(GLES20.GL_CULL_FACE);
GLES20.glVertexAttribPointer(vertexHandle, 3, GLES20.GL_FLOAT,
false, 0, mBuildingsModel.getVertices());
GLES20.glVertexAttribPointer(normalHandle, 3, GLES20.GL_FLOAT,
false, 0, mBuildingsModel.getNormals());
GLES20.glVertexAttribPointer(textureCoordHandle, 2,
GLES20.GL_FLOAT, false, 0, mBuildingsModel.getTexCoords());

GLES20.glEnableVertexAttribArray(vertexHandle);
GLES20.glEnableVertexAttribArray(normalHandle);
GLES20.glEnableVertexAttribArray(textureCoordHandle);

GLES20.glActiveTexture(GLES20.GL_TEXTURE0);
GLES20.glBindTexture(GLES20.GL_TEXTURE_2D,
mTextures.get(3).mTextureID[0]);
GLES20.glUniformMatrix4fv(mvpMatrixHandle, 1, false,
modelViewProjection, 0);
GLES20.glUniform1i(texSampler2DHandle, 0);
GLES20.glDrawArrays(GLES20.GL_TRIANGLES, 0,
mBuildingsModel.getNumObjectVertex());

SampleUtils.checkGLError("Renderer DrawBuildings");
}

SampleUtils.checkGLError("Render Frame");

}

GLES20.glDisable(GLES20.GL_DEPTH_TEST);

mRenderer.end();
}


private void printUserData(Trackable trackable)
{
String userData = (String) trackable.getUserData();
Log.d(LOGTAG, "UserData:Retreived User Data \"" + userData + "\"");
}


public void setTextures(Vector<Texture> textures)
{
mTextures = textures;

}

}


building.xml is another file with diffrent numbers of vertices and indices i'm Confused about the numbers in building.xml and in setVertx() ,setindcises() plz help.