[TOOL] acHelper | Just small themers Tool | 001 | 29.09.2012 - Android Themes

### Description:
I think that almost all themers gets tired when they needs to make resources-redirections file (at /res/xml/ folder).
### How to use it?
- Put themed icons to /acHelper/themed/ folder
- Run /acHelper/run.bat (If you're Linux user - launch achelper.jar by hands)
- Type icons prefix
- Enjoy
### Sources:
Code:
import java.io.File;
import java.io.IOException;
import java.io.FileWriter;
import java.util.Scanner;
import java.util.Date;
public class ThemeHelper {
private static final String VERSION_NAME = "0.1";
private static final String FOLDER_THEMED_NAME = "themed";
private static File mRootFolder = null;
public static void main(String[] args) {
try {
mRootFolder = new File(ThemeHelper.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath()).getParentFile();
} catch (Exception ex) { return; }
logln(3);
logln("Program:");
logln(" acHelper "+VERSION_NAME);
logln("Contact:");
logln(" 2012 (C) [email protected]");
logln(" <[email protected]>");
logln(1);
log("Type resources prefix: ");
Scanner input = new Scanner(System.in);
String prefix = input.nextLine();
input.close();
logln("- - - - - - - - - - - - - - - - - -");
long beginTime = new Date().getTime();
createResourceRedirectionsFile(mRootFolder.getPath()+"/"+FOLDER_THEMED_NAME, prefix);
logln("- - - - - - - - - - - - - - - - - -");
logln(" Elapsed time: "+(new Date().getTime()-beginTime)+"ms.");
}
private static void createResourceRedirectionsFile(String directory, String patch){
int i, i2;
log(" - Building list of files... ");
final File[] files = new File(directory).listFiles(); logln("Successfully.");
log(" - Parcing files... ");
int length = files.length; String[] names = new String[length]; int ctrl = 0;
for (i = 0; i<length; i++) {
names[i+ctrl] = files[i].getName();
int nameLength = names[i+ctrl].length();
for (i2 = 0; i2 < nameLength; i2++)
if (names[i+ctrl].charAt(i2)=='.')
break;
if (i2 == nameLength) ctrl--;
else names[i+ctrl]=names[i+ctrl].substring(0, i2);
}
length = length+ctrl; logln(ctrl==0 ? "Successfully." : "Has warnings!");
try {
log(" - Opening output file... ");
File file = new File(mRootFolder
, patch.substring(0, patch.length()-1)+".xml");
file.delete();
FileWriter writer = new FileWriter(file); logln("Successfully.");
log(" - Parcing and writing values... ");
int patchLength = patch.length();
for (i = 0; i < length; i++){
if (names[i].length()>patchLength && names[i].substring(0, patchLength).equals(patch))
writer.append("<item name=\"drawable/"+names[i].substring(patchLength, names[i].length())+"\">@drawable/"+names[i]+"</item>\n");
}
writer.flush();
writer.close();
logln("Successfully.");
} catch (Exception ex) {
logln("Error!");
}
}
/**
* Short named analog of System.out.print(String msg);
*/
private static void log(String str){
System.out.print(str);
}
/**
* Recursive dividers
*/
private static void logln(int number){
if (number>1) logln(number-1);
logln("");
}
/**
* Short named analog of System.out.println(String msg);
*/
private static void logln(String str){
System.out.println(str);
}
}
acHelper Tool. 2012 © AChep
If you want copy it, let me know about it and make a link to my profile and thread.
Regards, AChep.​

Reserved for renamer tool

Reserved for my greedy

Спасибо земляк!
Thanx AChep! :good:

What exactly is this tool?

Related

Java maze solver HELP

I've been working on trying to create a maze solver method using an enum, but it has not been going so well.
This is the enum class:
Code:
public enum Direction {
N, NE, E, SE, S, SW, W, NW, HERE;
/**
* Returns the X/column change on the screen that is associated with
* this direction: -1 for W, 0 for N/S, and +1 for E.
*/
public int getColModifier() {
int mod;
switch (this) {
case NW:
case W:
case SW:
mod = -1;
break;
case NE:
case E:
case SE:
mod = +1;
break;
default:
mod = 0;
break;
}
return mod;
}
/**
* Returns the Y/row change on the screen that is associated with
* this direction: -1 for N, 0 for E/W, and +1 for south.
*/
public int getRowModifier() {
int mod;
switch (this) {
case N:
case NE:
case NW:
mod = -1;
break;
case S:
case SE:
case SW:
mod = +1;
break;
default:
mod = 0;
break;
}
return mod;
}
/** As {@link #getColModifier()} */
public int getXModifier() {
return this.getColModifier();
}
/** As {@link #getRowModifier()} */
public int getYModifier() {
return this.getRowModifier();
}
/**
* Returns the direction that is the opposite of this one.
* For example, <code>Direction.NE.reverse() == Direction.SW</code>.
* (The opposite of HERE is still HERE though.)
*/
public Direction reverse() {
if (this == HERE) {
return this;
}else {
int reversed = (this.ordinal() + 4) % 8;
Direction[] dirs = Direction.values();
return dirs[reversed];
}
}
}
and this is the method that I have been trying to write:
Code:
public java.util.ArrayList<Direction> getPathToExit(){
for (int x=0; x<map.length; x++){
for (int y=0; y<map[x].length; y++){
if (map[x][y]=='S'){
this.startRow=x;
this.startCol=y;
}
}
}
System.out.println("start "+startRow+", "+startCol);
return getPathToExit(this.startRow, this.startCol);
}
private java.util.ArrayList<Direction> getPathToExit(int row, int col){
Direction [] dirs = Direction.values();
ArrayList<Direction> path = new ArrayList<Direction>();
getPathToExit(row, col);
if (row < 0 || col < 0 || row > map.length || col > map[row].length){
return path;
}
else if (map[row][col] != ' '){
return path;
}
else if (map[row][col] == 'E'){
path.add(Direction.HERE);
return path;
}
else {
for (int x=0; x<dirs.length-1; x++){
map[row][col]='x';
int nextRow = row + dirs[x].getRowModifier();
int nextCol = col + dirs[x].getColModifier();
path = getPathToExit(nextRow, nextCol);
}
}
return path;
}
The problem I am having is that I keep getting stackoverflowerrors or the piece does not move (tested this by printing what row/col it is on), it would stay on the same tile then crash.
Thanks in advance.

[Q]scan for ble device

I'm trying to develop an app to scan for a BLE device. However, it only scans one time. I tried to use a while loop to loop it but it hangs there. The scanning part is at the proceed function:
Code:
package com.example.user.myfriend;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Handler;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import org.w3c.dom.Text;
public class MainActivity extends ActionBarActivity {
BluetoothAdapter mBluetoothAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
mBluetoothAdapter = bluetoothManager.getAdapter();
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
hello();
}
public void hello() {
if (mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled()) {
Intent enableBluetooth = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBluetooth, 1);
}
proceed();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
if (resultCode == RESULT_OK) {
proceed();
}
}
super.onActivityResult(requestCode, resultCode, data);
}
private BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() {
public void onLeScan(final BluetoothDevice device, final int rssi, final byte[] scanRecord) {
int startByte = 2;
boolean patternFound = false;
while (startByte <= 5) {
if (((int) scanRecord[startByte + 2] & 0xff) == 0x02 && //Identifies an iBeacon
((int) scanRecord[startByte + 3] & 0xff) == 0x15) { //Identifies correct data length
patternFound = true;
break;
}
startByte++;
}
if (patternFound) {
//Convert to hex String
byte[] uuidBytes = new byte[16];
System.arraycopy(scanRecord, startByte + 4, uuidBytes, 0, 16);
String hexString = bytesToHex(uuidBytes);
//Here is your UUID
String uuid = hexString.substring(0, 8) + "-" +
hexString.substring(8, 12) + "-" +
hexString.substring(12, 16) + "-" +
hexString.substring(16, 20) + "-" +
hexString.substring(20, 32);
//Here is your Major value
int major = (scanRecord[startByte + 20] & 0xff) * 0x100 + (scanRecord[startByte + 21] & 0xff);
//Here is your Minor value
int minor = (scanRecord[startByte + 22] & 0xff) * 0x100 + (scanRecord[startByte + 23] & 0xff);
if (major == 1) {
RelativeLayout hai = (RelativeLayout) findViewById(R.id.hai);
hai.setBackgroundColor(Color.YELLOW);
}
if (major == 2) {
RelativeLayout hai = (RelativeLayout) findViewById(R.id.hai);
hai.setBackgroundColor(Color.RED);
}
}
}
};
private static String bytesToHex(byte[] bytes) {
final char[] hexArray = "0123456789ABCDEF".toCharArray();
char[] hexChars = new char[bytes.length * 2];
for (int j = 0; j < bytes.length; j++) {
int v = bytes[j] & 0xFF;
hexChars[j * 2] = hexArray[v >>> 4];
hexChars[j * 2 + 1] = hexArray[v & 0x0F];
}
return new String(hexChars);
}
public void proceed() {
boolean scanning = true;
mBluetoothAdapter.startLeScan(mLeScanCallback);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
// @Override
public void run() {
mBluetoothAdapter.stopLeScan(mLeScanCallback);
}
}, 50000000);
}
Code:

PHP, database, SQL app

hi.
i make login and register app' that use php,SQL and database, all work excellent,
I add a few thing like: user can upload image (base64) to his php folder and more,
So now i am stock when i want get image back (base64) from php folder
this my code:
Code:
public class SQLiteHandler extends SQLiteOpenHelper {
private static final String TAG = SQLiteHandler.class.getSimpleName();
// All Static variables
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "u294011906_camel";
// Login table name
private static final String TABLE_LOGIN = "login";
// Login Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_NAME = "name";
private static final String KEY_EMAIL = "email";
private static final String KEY_UID = "uid";
private static final String KEY_CREATED_AT = "created_at";
public SQLiteHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Creating Tables
@Override
public void onCreate(SQLiteDatabase db) {
String CREATE_LOGIN_TABLE = "CREATE TABLE " + TABLE_LOGIN + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
+ KEY_EMAIL + " TEXT UNIQUE," + KEY_UID + " TEXT,"
+ KEY_CREATED_AT + " TEXT" + ")";
db.execSQL(CREATE_LOGIN_TABLE);
Log.d(TAG, "Database tables created");
}
// Upgrading database
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_LOGIN);
// Create tables again
onCreate(db);
}
/**
* Storing user details in database
* */
public void addUser(String name, String email, String uid, String created_at) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, name); // Name
values.put(KEY_EMAIL, email); // Email
values.put(KEY_UID, uid); // Email
values.put(KEY_CREATED_AT, created_at); // Created At
// Inserting Row
long id = db.insert(TABLE_LOGIN, null, values);
db.close(); // Closing database connection
Log.d(TAG, "New user inserted into sqlite: " + id);
}
/**
* Getting user data from database
* */
public HashMap<String, String> getUserDetails() {
HashMap<String, String> user = new HashMap<String, String>();
String selectQuery = "SELECT * FROM " + TABLE_LOGIN;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// Move to first row
cursor.moveToFirst();
if (cursor.getCount() > 0) {
user.put("name", cursor.getString(1));
user.put("email", cursor.getString(2));
user.put("uid", cursor.getString(3));
user.put("created_at", cursor.getString(4));
}
cursor.close();
db.close();
// return user
Log.d(TAG, "Fetching user from Sqlite: " + user.toString());
return user;
}
/**
* Getting user login status return true if rows are there in table
* */
public int getRowCount() {
String countQuery = "SELECT * FROM " + TABLE_LOGIN;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
int rowCount = cursor.getCount();
db.close();
cursor.close();
// return row count
return rowCount;
}
/**
* Re crate database Delete all tables and create them again
* */
public void deleteUsers() {
SQLiteDatabase db = this.getWritableDatabase();
// Delete All Rows
db.delete(TABLE_LOGIN, null, null);
db.close();
Log.d(TAG, "Deleted all user info from sqlite");
}
}
Code:
/**
* Function to upload profile picture
* */
private void uploadProfilePicture(final String image,final String emailToSend)
{
// Tag used to cancel the request
pictureCheck = "null";
String tag_string_req = "profile_image";
pDialog.setMessage("Upload profile picture ...");
showDialog();
StringRequest strReq = new StringRequest(Request.Method.POST, AppConfig.URL_REGISTER, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.d(TAG, "Upload profile picture Response: " + response.toString());
hideDialog();
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
if (!error) {
Toast.makeText(getApplicationContext(), "Your new profile picture sucessfully uploaded", Toast.LENGTH_LONG).show();
} else {
// Error occurred in registration. Get the error
// message
String errorMsg = jObj.getString("error_msg");
Toast.makeText(getApplicationContext(),
errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Profile picture Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
hideDialog();
}
})
{
@Override
protected Map<String, String> getParams()
{
// Posting params to register url
Map<String, String> params = new HashMap<String, String>();
params.put("tag", "profile_image");
params.put("ImageName", emailToSend);
params.put("base64", image);
params.put("email", emailToSend);
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
And Some code how i am get details of user
Code:
// Fetching user details from sqlite
HashMap<String, String> user = db.getUserDetails();
String name = user.get("name");
String email = user.get("email");
EmailtoSend = email;
// Displaying the user details on the screen
txtName.setText(name);
i want get profile image from php folder, i put image(bae64) to folder that open when user register. All work excellent, when user upload image, image uploaded to user folder with name "profile_image"
so now i want get this image when login open app/login
someone can help me?
if someone have skype it's will be great

ArrayList IndexOutOfBound Error

Hi! I am currently doing on a project and I keep hitting the same error despite making changes. I have been hitting indexOutOfBound error and unable to delete my listView item because of that error. I am doing on Tab and Database. Can anyone help me with my error and problem? Thank you!!
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 itp231.dba.nyp.com.mabel_createchallenge.mabel_tabs.mabelUncompleted_Tab1$2.onClick(mabelUncompleted_Tab1.java:124)
at android.support.v7.app.AlertController$ButtonHandler.handleMessage(AlertController.java:157)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Here are by Java Codes
Code:
package itp231.dba.nyp.com.mabel_createchallenge;
import android.content.Context;
import android.database.Cursor;
import java.util.ArrayList;
import itp231.dba.nyp.com.mabel_createchallenge.mabel_database.mabel_MyDBAdpater;
/*
* Created by Guest Account on 13/7/2016.
*/
public class mabel_creatingChallengeApp {
private static mabel_creatingChallengeApp ourInstance = new mabel_creatingChallengeApp();
public static mabel_creatingChallengeApp getInstance() {
return ourInstance;
}
public mabel_creatingChallengeApp() {
challengesCreatedAL = new ArrayList<mabel_challenges>();
}
//* for mabelUncompleted_tab1.java */
private ArrayList<mabel_challenges> challengesCreatedAL;
public ArrayList<mabel_challenges> getArray() {
return challengesCreatedAL;
} //getting the array from ArrayList<mabel_challenges>
public ArrayList<mabel_challenges> getChallengesCreatedAL() {
return challengesCreatedAL;
}
//add and delete entries in the database
//add to database
//context --> context of current state of the application/object
//call it to get information regarding another part of your program (activity and package/application)
public static long addToDatabase(mabel_challenges challenges, Context c) {
mabel_MyDBAdpater db = new mabel_MyDBAdpater(c);
db.open();
long rowIDofInsertEntry = db.insertEntry(challenges);
db.close();
return rowIDofInsertEntry;
}
public static boolean deleteFromDatabase(int rowID, Context c) {
mabel_MyDBAdpater db = new mabel_MyDBAdpater(c);
db.open();
boolean updateStatus = db.removeEntry(rowID);
db.close();
return updateStatus;
}
public static boolean updateDatabase(mabel_challenges cc, int rowID, Context c) {
mabel_MyDBAdpater db = new mabel_MyDBAdpater(c);
db.open();
boolean updateStatus = db.updateEntry(rowID, cc);
db.close();
return updateStatus;
}
//populate array --> retrieve the array
//get the context --> get the content from the page
//store all retrieve data from database
public void populateArrayFromDB(Context c) {
challengesCreatedAL.clear();
mabel_MyDBAdpater db = new mabel_MyDBAdpater(c);
db.open();
Cursor cur = db.retrieveAllEntriesCursor();
cur.moveToFirst();
while(cur.moveToNext()) {
int rowID = cur.getInt(mabel_MyDBAdpater.COLUMN_KEY_ID);
String nameOfChallenge = cur.getString(mabel_MyDBAdpater.COLUMN_NAME_ID);
String descOfChallenge = cur.getString(mabel_MyDBAdpater.COLUMN_DESC_ID);
String durationOfChallenge = cur.getString(mabel_MyDBAdpater.COLUMN_DURATION_ID);
mabel_challenges newChallenge = new mabel_challenges(rowID, nameOfChallenge, descOfChallenge, durationOfChallenge);
challengesCreatedAL.add(newChallenge);
}
db.close();
}
}
Code:
package itp231.dba.nyp.com.mabel_createchallenge.mabel_tabs;
/*
fragment is part of an activity
*/
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
import itp231.dba.nyp.com.mabel_createchallenge.R;
import itp231.dba.nyp.com.mabel_createchallenge.mabel_EditChallengeActivity;
import itp231.dba.nyp.com.mabel_createchallenge.mabel_challengeDetailActivity;
import itp231.dba.nyp.com.mabel_createchallenge.mabel_challenges;
import itp231.dba.nyp.com.mabel_createchallenge.mabel_creatingChallengeApp;
import itp231.dba.nyp.com.mabel_createchallenge.mabel_database.mabel_myChallengesListAdapter;
public class mabelUncompleted_Tab1 extends Fragment{
ListView listOfItemsLV;
ArrayList<mabel_challenges> challengesCreatedAL;
mabel_creatingChallengeApp cc;
public int selectedItem;
mabel_challenges c;
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.mabel_tab_1_uncompleted, container, false);
listOfItemsLV = (ListView) v.findViewById(R.id.challengesUncompletedLV);
registerForContextMenu(listOfItemsLV);
// addPage = (ImageButton) v.findViewById(R.id.addPage);
//calling out Instance Variable before the adapater
//to get challenges item on the list item
cc = mabel_creatingChallengeApp.getInstance();
//retrieve array from database
cc.populateArrayFromDB(getActivity().getApplicationContext()); //because is fragment so getActivity --> fragment is the contents in the tab -->getActivity will get the whole screen contents including contents in the tab
challengesCreatedAL = cc.getArray();
//Adapter for List View
mabel_myChallengesListAdapter challengesAdapter = new mabel_myChallengesListAdapter(getActivity(), challengesCreatedAL);
listOfItemsLV.setAdapter(challengesAdapter);
listOfItemsLV.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
//getting the position of item in the array list
mabel_challenges c = challengesCreatedAL.get(i);
//intent for challenge detail
//mabel_challengeDetailActivity.class --> get to here
Intent viewDetailsIntent = new Intent(getActivity().getApplicationContext(), mabel_challengeDetailActivity.class);
//put extra --> Add extended data to the intent
viewDetailsIntent.putExtra(mabel_challenges.INTENT_NAME_CHALLENGENAME, c.getName());
viewDetailsIntent.putExtra(mabel_challenges.INTENT_NAME_DESCRIPTION, c.getDesc());
viewDetailsIntent.putExtra(mabel_challenges.INTENT_NAME_DURATION, c.getDuration());
viewDetailsIntent.putExtra("position", i);
startActivity(viewDetailsIntent);
}
});
return v;
}
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
menu.setHeaderTitle("Options");
menu.add(1,1,1, "Edit");
menu.add(1,2,2, "Delete");
}
public boolean onContextItemSelected(MenuItem item) {
final AdapterView.AdapterContextMenuInfo menuInfo = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
selectedItem = menuInfo.position;
//mabel_challenges c = challengesCreatedAL.get(selectedItem);
switch(item.getItemId()) {
case 1:
//edit challenge
Intent editChallenge = new Intent (getActivity(), mabel_EditChallengeActivity.class);
editChallenge.putExtra(mabel_challenges.INTENT_NAME_ARRAY_ITEM, selectedItem);
startActivity(editChallenge);
break;
case 2:
//delete challenge
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(getActivity());
dialogBuilder.setMessage("Confirm delete ?");
dialogBuilder.setPositiveButton("Delete" ,new DialogInterface.OnClickListener(){
@Override
public void onClick(DialogInterface dialogInterface, int i) {
mabel_myChallengesListAdapter challengeAdapter = new mabel_myChallengesListAdapter(getActivity().getApplicationContext(), challengesCreatedAL);
listOfItemsLV.setAdapter(challengeAdapter);
challengeAdapter.notifyDataSetChanged();
//prac 7b sales tracker -->delete the item
//selectedItem is the index of the array
mabel_creatingChallengeApp ca = mabel_creatingChallengeApp.getInstance();
int challengeId = ca.getArray().get(selectedItem).getId();
mabel_creatingChallengeApp.deleteFromDatabase(challengeId, getActivity().getApplicationContext());
ca.populateArrayFromDB(getActivity().getApplicationContext());
Toast.makeText(getActivity().getApplicationContext(), "Deleted!", Toast.LENGTH_LONG).show();
}
});
dialogBuilder.setNegativeButton("Cancel",new DialogInterface.OnClickListener(){
@Override
public void onClick(DialogInterface dialogInterface, int i) {
// dialogBuilder.setCancelable(true);
Toast.makeText(getActivity().getApplicationContext(), "Cancelled!", Toast.LENGTH_LONG).show();
}
});
dialogBuilder.create();
dialogBuilder.show();
break;
}
return true;
}
@Override
public void onResume() {
super.onResume();
cc.populateArrayFromDB(getActivity().getApplicationContext());
}
}
Code:
package itp231.dba.nyp.com.mabel_createchallenge.mabel_database;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import itp231.dba.nyp.com.mabel_createchallenge.mabel_challenges;
import itp231.dba.nyp.com.mabel_createchallenge.mabel_creatingChallengeApp;
/**
* Created by Guest Account on 13/7/2016.
* for uncompleted Tab
*/
public class mabel_MyDBAdpater {
private static final String DATABASE_NAME = "Challenges.db"; //name of database
private static final String DATABASE_TABLE = "ChallengesDatabase"; //database table name
private static final int DATABASE_VERSION = 2;
private SQLiteDatabase _db; //sqlite database handler
private final Context context; //current context
public static final String KEY_ID = "_id";
public static final int COLUMN_KEY_ID = 0;
public static final String ENTRY_CHALLENGE_NAME = "Name"; //name of column
public static final int COLUMN_NAME_ID = 1; //retrieval, position
public static final String ENTRY_CHALLENGE_DESC = "Description";
public static final int COLUMN_DESC_ID = 2;
public static final String ENTRY_CHALLENGE_DURATION = "Duration";
public static final int COLUMN_DURATION_ID = 3;
protected static final String DATABASE_CREATE = "create table " + DATABASE_TABLE + " " + "(" + KEY_ID + " integer primary key autoincrement, " +
ENTRY_CHALLENGE_NAME + " Text, " + ENTRY_CHALLENGE_DESC + " Text, " + ENTRY_CHALLENGE_DURATION + " Text);";
//making debugging easier
//a fix pid for Eclipse debugger
//open and close method
private String mabel_MyDBAdapter_LOG_CAT = "MY_LOG";
private MyDBOpenHelper dbHelper;
public mabel_MyDBAdpater(Context _context)
{
this.context = _context;
dbHelper = new MyDBOpenHelper(context, DATABASE_NAME, null, DATABASE_VERSION); //help to create object
}
public void close()
{
_db.close();
Log.w(mabel_MyDBAdapter_LOG_CAT, "DB closed");
}
public void open() throws SQLiteException
{
try
{
_db = dbHelper.getWritableDatabase();
Log.w(mabel_MyDBAdapter_LOG_CAT, "DB opened as writable database");
}
catch(SQLiteException e)
{
_db = dbHelper.getReadableDatabase();
Log.w(mabel_MyDBAdapter_LOG_CAT, "DB opened as readable database");
}
}
public long insertEntry(mabel_challenges cc)
{
// Create a new record
ContentValues newEntryValues = new ContentValues();
// Assign values for each row
newEntryValues.put(ENTRY_CHALLENGE_NAME, cc.getName());
newEntryValues.put(ENTRY_CHALLENGE_DESC, cc.getDesc());
newEntryValues.put(ENTRY_CHALLENGE_DURATION, cc.getDuration());
// Insert the row
Log.w(mabel_MyDBAdapter_LOG_CAT, "Inserted EntryName = " + cc.getName()
+ " EntryDesc = " + cc.getDesc() + " EntryDuration = " + cc.getDuration() + " into table " + DATABASE_TABLE);
return _db.insert(DATABASE_TABLE, null, newEntryValues);
}
//removing data
public boolean removeEntry(long _rowIndex)
{
if (_db.delete(DATABASE_TABLE, KEY_ID + " = " + _rowIndex, null) <= 0)
{
Log.w(mabel_MyDBAdapter_LOG_CAT, "Removing entry where id = "
+ _rowIndex + " Failed");
return false;
}
Log.w(mabel_MyDBAdapter_LOG_CAT, "Removing entry where id = "
+ _rowIndex + " Success");
return true;
}
//update method
public boolean updateEntry(long rowIndex, mabel_challenges cc) {
ContentValues updateValues = new ContentValues();
mabel_creatingChallengeApp ca = mabel_creatingChallengeApp.getInstance();
updateValues.put(ENTRY_CHALLENGE_NAME, cc.getName());
updateValues.put(ENTRY_CHALLENGE_DESC, cc.getDesc());
updateValues.put(ENTRY_CHALLENGE_DURATION, cc.getDuration());
String where = KEY_ID + "=" + rowIndex; //selected id for updating data
Log.w(mabel_MyDBAdapter_LOG_CAT, "Updated Challenge Name = " + cc.getName() + "Update Challenge Description = " + cc.getDesc() + "Update Duration = " + cc.getDuration() + " into table " +DATABASE_TABLE);
if (_db.update(DATABASE_TABLE, updateValues, where, null) <= 0) {
return true; //return success
}
return false; //newer update anything
}
//retrieve method
public Cursor retrieveAllEntriesCursor()
{
Cursor c = null;
try
{
c = _db.query(DATABASE_TABLE, new String[] {KEY_ID,ENTRY_CHALLENGE_NAME, ENTRY_CHALLENGE_DESC, ENTRY_CHALLENGE_DURATION}, null, null, null, null, null);
}
catch(SQLiteException e)
{
Log.w(mabel_MyDBAdapter_LOG_CAT, "Retrieve fail!");
}
return c;
}
public class MyDBOpenHelper extends SQLiteOpenHelper
{
public MyDBOpenHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version)
{
super(context, name, factory, version);
// TODO Auto-generated constructor stub
}
@Override //compulsory method
public void onCreate(SQLiteDatabase db)
{
// TODO Auto-generated method stub
db.execSQL(DATABASE_CREATE);
Log.w(mabel_MyDBAdapter_LOG_CAT, "Helper : DB " + DATABASE_TABLE + " Created!!");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
// TODO Auto-generated method stub
}
} // End of myDBOpenHelper
}
Can help me to see what's wrong? Thank you !!!!
I can't read the all code, it's too long, but ai think that you want to access for example array [5], but array length is smaller.
Trimis de pe al meu Sony Z2 D6503
mabelll said:
Hi! I am currently doing on a project and I keep hitting the same error despite making changes. I have been hitting indexOutOfBound error and unable to delete my listView item because of that error. I am doing on Tab and Database. Can anyone help me with my error and problem? Thank you!!
Click to expand...
Click to collapse
Uncompleted_Tab1 onClick(mabelUncompleted _Tab1.java:124)
cannot see the line number. check line 124 for yourself.

[HELP] why Zygisk need to force dlopen /system/bin/app_process

1. Why use android_dlopen_ext in the first_stage_entry function to force open /system/bin/app_process?
2. Why dlclose immediately after dlopen in second_stage_entry? Why do it?
// native/jni/zygisk/entry.cpp
static void first_stage_entry() {
android_logging();
ZLOGD("inject 1st stage\n");
char path[PATH_MAX];
char buf[256];
char *ld = getenv("LD_PRELOAD");
if (char *c = strrchr(ld, ':')) {
*c = '\0';
strlcpy(path, c + 1, sizeof(path));
setenv("LD_PRELOAD", ld, 1); // Restore original LD_PRELOAD
} else {
unsetenv("LD_PRELOAD");
strlcpy(path, ld, sizeof(path));
}
// Force the linker to load the library on top of ourselves, so we do not
// need to unmap the 1st stage library that was loaded with LD_PRELOAD.
int fd = xopen(path, O_RDONLY | O_CLOEXEC);
// Use fd here instead of path to make sure inode is the same as 2nd stage
snprintf(buf, sizeof(buf), "%d", fd);
setenv(MAGISKFD_ENV, buf, 1);
struct stat s{};
xfstat(fd, &s);
android_dlextinfo info {
.flags = ANDROID_DLEXT_FORCE_LOAD | ANDROID_DLEXT_USE_LIBRARY_FD,
.library_fd = fd,
};
// 通过 inode 在 maps 中搜索 /sbin/magisk(app_process) 对应的内存区域
auto [addr, size] = find_map_range(path, s.st_ino);
if (addr && size) {
// 下面使用 android_dlopen_ext 重复加载 /sbin/magisk,
// 通过 reserved_addr 强制覆盖内存.
info.flags |= ANDROID_DLEXT_RESERVED_ADDRESS;
info.reserved_addr = addr;
// The existing address is guaranteed to fit, as 1st stage and 2nd stage
// are exactly the same ELF (same inode). However, the linker could over
// estimate the required size and refuse to dlopen. The estimated size
// is not accurate so size the size to unlimited.
info.reserved_size = -1;
}
setenv(INJECT_ENV_2, "1", 1);
// Force dlopen ourselves to make ourselves dlclose-able.
// After this call, all global variables will be reset.
// 重复加载 /sbin/magisk 到内存, 覆盖之后全局变量将被重置
// 这里为什么要强制 dlopen? 只是为了以后可以使用 dlclose 释放 zygisk 吗????
android_dlopen_ext(path, RTLD_LAZY, &info);
}
Code:
// // native/jni/zygisk/entry.cpp
static void second_stage_entry() {
zygisk_logging();
ZLOGD("inject 2nd stage\n");
char path[PATH_MAX];
MAGISKTMP = getenv(MAGISKTMP_ENV);
int fd = parse_int(getenv(MAGISKFD_ENV));
snprintf(path, sizeof(path), "/proc/self/fd/%d", fd);
xreadlink(path, path, PATH_MAX);
android_dlextinfo info {
.flags = ANDROID_DLEXT_USE_LIBRARY_FD,
.library_fd = fd,
};
// 这里的dlopen并不会重新调用 zygisk_init, 这里是假的dlopen? 只是为了下一行的 dlclose?
// 为什么要这样做?
// Why do this?
self_handle = android_dlopen_ext(path, RTLD_LAZY, &info);
dlclose(self_handle);
close(fd);
unsetenv(MAGISKTMP_ENV);
unsetenv(MAGISKFD_ENV);
sanitize_environ();
hook_functions();
}

Categories

Resources