Если другие люди сталкиваются с чем-то похожим и приходят на этот пост, проблема, которую я могу, может сэкономить вам некоторое время. Может быть, не связано с проблемой OP, но def связано с исключением ActivityNotFound.
Я пытался загрузить активность с помощью:
Intent intent = new Intent( this, class );
Однако я постоянно продолжал получать ActivityNotFoundException
, хотя я проверял и повторно проверял код несколько раз.
Это исключение, которое я получал, на самом деле не было вызвано намерением, но какой-то код, который я запускал внутри загруженной активности, бросая RuntimeException
, (моя проблема была вызвана Typeface.createFromAsset()
)
Возможно, что вы работаете с аналогичным RuntimeException в своей деятельности.
Чтобы убедиться, что это так, введите код своей цели в блоках try catch. Например:
try {
/* your code */
...
} catch ( ActivityNotFoundException e) {
e.printStackTrace();
}
Запустите приложение снова и проверьте свой LogCat, если это та же проблема, вы получите исключение RuntimeException с записью «Caused By:», указывающей на вашу актуальную проблему.
Я потратил хороший час, пытаясь понять это. Надеюсь, это может сэкономить некоторое время.
Ссылка на означает выбор адреса существующей переменной (с помощью & amp;) для установки переменной указателя. Чтобы быть действительным, указатель должен быть установлен на адрес переменной того же типа, что и указатель, без звездочки:
int c1;
int* p1;
c1 = 5;
p1 = &c1;
//p1 references c1
Выделение указателя означает использование оператора * (символ звездочки) для доступа к значению, хранящемуся у указателя: ПРИМЕЧАНИЕ. Значение, хранящееся по адресу указателя, должно быть значением ОДНОГО ТИПА как тип переменной, на которую указывает «указатель», но есть нет гарантии , это так, если указатель не был установлен правильно. Тип переменной, на которую указывает указатель, - это тип, который меньше, чем самая внешняя звездочка.
int n1;
n1 = *p1;
Неверное разыменование может вызвать или не вызвать сбои:
Недопустимая ссылка скорее всего вызовет ошибки компилятора, чем сбои, но не стоит полагаться на компилятор для этого.
Ссылки:
http://www.codingunit.com/cplusplus-tutorial-pointers-reference-and-dereference-operators
& is the reference operator and can be read as “address of”.
* is the dereference operator and can be read as “value pointed by”.
http://www.cplusplus.com/doc/tutorial/pointers/
& is the reference operator
* is the dereference operator
http://en.wikipedia.org/wiki / Dereference_operator
The dereference operator * is also called the indirection operator.
Для начала вы имеете их назад: &
является ссылкой, а *
является разыменованием.
Ссылка на переменную означает доступ к адресу памяти переменной:
int i = 5;
int * p;
p = &i; //&i returns the memory address of the variable i.
Выделение переменной означает доступ к переменной, хранящейся по адресу памяти:
int i = 5;
int * p;
p = &i;
*p = 7; //*p returns the variable stored at the memory address stored in p, which is i.
//i is now 7
Я всегда слышал, что они использовались в противоположном смысле:
&
является ссылочным оператором - он дает ссылку (указатель) на какой-либо объект *
- это оператор разыменования - он принимает ссылку (указатель) и возвращает вам упомянутый объект; найти следующее объяснение:
int main()
{
int a = 10;// say address of 'a' is 2000;
int *p = &a; //it means 'p' is pointing[referencing] to 'a'. i.e p->2000
int c = *p; //*p means dereferncing. it will give the content of the address pointed by 'p'. in this case 'p' is pointing to 2000[address of 'a' variable], content of 2000 is 10. so *p will give 10.
}
заключение:
&
[адресный оператор] используется для ссылки. *
[оператор звезды] используется для удаления ссылок. &
является ссылочным оператором. Он будет ссылаться на адрес памяти на переменную-указатель.
int *p;
int a=5;
p=&a; // Here Pointer variable p refers to the address of integer variable a.
Оператор разыменования *
используется переменной указателя для прямое обращение к значению переменной вместо адреса памяти.
int *p;
int a=5;
p=&a;
int value=*p; // Value variable will get the value of variable a that pointer variable p pointing to.
Контекст, в котором находится *, иногда путает смысл.
// when declaring a function
int function(int*); // This function is being declared as a function that takes in an 'address' that holds a number (so int*), it's asking for a 'reference', interchangeably called 'address'. When I 'call'(use) this function later, I better give it a variable-address! So instead of var, or q, or w, or p, I give it the address of var so &var, or &q, or &w, or &p.
//even though the symbol ' * ' is typically used to mean 'dereferenced variable'(meaning: to use the value at the address of a variable)--despite it's common use, in this case, the symbol means a 'reference', again, in THIS context. (context here being the declaration of a 'prototype'.)
//when calling a function
int main(){
function(&var); // we are giving the function a 'reference', we are giving it an 'address'
}
Итак, в контексте , объявляющего тип , такой как int или char, мы использовали бы dereferencer '*' на самом деле означает ссылку (адрес) , что делает ее запутанной, если вы видите сообщение об ошибке от компилятора: «Ожидание char *», запрашивающее адрес.
В этом случае, когда символ * находится после типа (int, char и т. д.), компилятор ожидает адрес переменной. Мы приводим это с помощью ссылочного оператора, alos, называемого адресом оператора & amp; 'перед переменной. Более того, в случае, когда я только что составил выше, компилятор ожидает, что адрес будет содержать значение символа, а не число. (введите char * == адрес значения, имеющего символ).
int* p;
int *a; // both are 'pointer' declarations. We are telling the compiler that we will soon give these variables an address (with &).
int c = 10; //declare and initialize a random variable
//assign the variable to a pointer, we do this so that we can modify the value of c from a different function regardless of the scope of that function (elaboration in a second)
p = c; //ERROR, we assigned a 'value' to this 'pointer'. We need to assign an 'address', a 'reference'.
p = &c; // instead of a value such as: 'q',5,'t', or 2.1 we gave the pointer an 'address', which we could actually print with printf(), and would be something like
//so
p = 0xab33d111; //the address of c, (not specifically this value for the address, it'll look like this though, with the 0x in the beggining, the computer treats these different from regular numbers)
*p = 10; // the value of c
a = &c; // I can still give c another pointer, even though it already has the pointer variable "p"
*a = 10;
a = 0xab33d111;
Подумайте о том, что каждая переменная имеет позицию (или значение индекса, если вы знакомы с массивами) и значение. Может потребоваться некоторое привыкание - подумать о каждой переменной, имеющей два значения, одно значение - это положение, физически сохраненное с электричеством на вашем компьютере, и значение, представляющее любое количество или буквы, которые программист хочет сохранить.
//Why it's used
int function(b){
b = b + 1; // we just want to add one to any variable that this function operates on.
}
int main(){
int c = 1; // I want this variable to be 3.
function(c);
function(c);// I call the function I made above twice, because I want c to be 3.
// this will return c as 1. Even though I called it twice.
// when you call a function it makes a copy of the variable.
// so the function that I call "function", made a copy of c, and that function is only changing the "copy" of c, so it doesn't affect the original
}
//let's redo this whole thing, and use pointers
int function(int* b){ // this time, the function is 'asking' (won't run without) for a variable that 'points' to a number-value (int). So it wants an integer pointer--an address that holds a number.
*b = *b + 1; //grab the value of the address, and add one to the value stored at that address
}
int main(){
int c = 1; //again, I want this to be three at the end of the program
int *p = &c; // on the left, I'm declaring a pointer, I'm telling the compiler that I'm about to have this letter point to an certain spot in my computer. Immediately after I used the assignment operator (the ' = ') to assign the address of c to this variable (pointer in this case) p. I do this using the address-of operator (referencer)' & '.
function(p); // not *p, because that will dereference. which would give an integer, not an integer pointer ( function wants a reference to an int called int*, we aren't going to use *p because that will give the function an int instead of an address that stores an int.
function(&c); // this is giving the same thing as above, p = the address of c, so we can pass the 'pointer' or we can pass the 'address' that the pointer(variable) is 'pointing','referencing' to. Which is &c. 0xaabbcc1122...
//now, the function is making a copy of c's address, but it doesn't matter if it's a copy or not, because it's going to point the computer to the exact same spot (hence, The Address), and it will be changed for main's version of c as well.
}
Внутри каждого блока он копирует переменные (если они есть), которые передаются (через параметры внутри «()» s). Внутри этих блоков изменения переменной приводятся к копии этой переменной, переменная использует одни и те же буквы, но имеет другой адрес (от оригинала). Используя адрес «ссылка» оригинала, мы можем изменить переменную, используя блок вне основного или внутри дочернего элемента main.