Ребят кому не лень помогите с поиском ошибок

SQLite, Preferences, файлы, SD, Content Provider, XML, JSON
Ответить
iandryxa
Сообщения: 58
Зарегистрирован: 23 янв 2014, 20:40

Ребят кому не лень помогите с поиском ошибок

Сообщение iandryxa » 18 фев 2014, 21:37

Ребят срочно нужна помощь! программер я начинающий поэтому не судите строго, вообщем есть такие небольшие наработки по калькулятору с функцией истории, вообщем вот такой код

MainActivity.java
package com.example1.calc;

import java.util.ArrayList;


import android.app.Activity;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.TextView;

public class MainActivity extends Activity implements OnClickListener{

private TextView editText1;
private TextView editText2;

private RadioButton radioButton1;
private RadioButton radioButton2;
private RadioButton radioButton3;
private RadioButton radioButton4;

private ListView lvHistory;

private Button button1;
SQLiteDatabase db;


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

editText1 = (TextView) findViewById(R.id.editText1);
editText2 = (TextView) findViewById(R.id.editText2);
radioButton1 = (RadioButton) findViewById(R.id.radioButton1);
radioButton2 = (RadioButton) findViewById(R.id.radioButton2);
radioButton3 = (RadioButton) findViewById(R.id.radioButton3);
radioButton4 = (RadioButton) findViewById(R.id.radioButton4);
button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(this);

//восстанавливам историю прошлых вычеслений из БД
db = (new DBHelper(this)).getWritableDatabase();
showHistory();
}


@Override
public void onClick(View v) {

//проверяем пользовательский ввод
Integer first = null;
Integer Second = null;
String historyLine = "";

try{
first = Integer.parseInt(editText1.getText().toString());
}catch(Exception ex){
editText1.setError("Неправильный формат");
}

try{
Second = Integer.parseInt(editText2.getText().toString());
}catch(Exception ex){
editText2.setError("Неправильный формат");
}

//Сообщаем о ВСЕХ ошибках ввода и выходим
if(first == null || Second == null)return;
if(radioButton1.isChecked() && Second == 0)
{
editText2.setError("Деление на 0");
return;
}

//подсчитываем и выводим результат
String action = "";
Integer result = null;
if(radioButton1.isChecked()){result = first / Second; action = "/";};
if(radioButton2.isChecked()){result = first * Second; action = "*";};
if(radioButton3.isChecked()){result = first + Second; action = "+";};
if(radioButton4.isChecked()){result = first - Second; action = "-";};
historyLine = first.toString()+ action + Second.toString() + "=" + result;

//отчищаем поля ввода для следующего вычисления
editText1.setText("");
radioButton1.setChecked(false);
radioButton2.setChecked(false);
radioButton3.setChecked(false);
radioButton4.setChecked(false);
editText2.setText("");

//сохраняем рехультат в базу данных
ContentValues v1 = new ContentValues();
v1.put(DBHelper.A_EXPRESSION, historyLine);
db.insert(DBHelper.TABLE_NAME, null, v1);

//обновляем историю
showHistory();
}

void showHistory(){
Cursor c = db.query(DBHelper.TABLE_NAME,DBHelper.PROJECTION,null, null, null, null, DBHelper.A_ID);
c.moveToLast();

ArrayList<String> historyList = new ArrayList<String>();
while(!c.isBeforeFirst()){
historyList.add(c.getString(c.getColumnIndex(DBHelper.A_EXPRESSION)));
c.moveToPrevious();
}
c.close();

lvHistory.setAdapter(
new ArrayAdapter<String>(
this,
android.R.layout.simple_list_item_1,
historyList));
}


}



DBHelper.java
package com.example1.calc;

import android.app.Activity;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DBHelper extends SQLiteOpenHelper {

public static final int DB_VERSION = 1;
public static final String DB_NAME = "Calc.db";
public static final String TABLE_NAME = "History";

public final static String A_ID = "_id";
public final static String A_EXPRESSION = "expression";

public static String[] PROJECTION = {A_ID,A_EXPRESSION};

private SQLiteDatabase db;
public DBHelper (Context context){
super(context, DB_NAME, null, DB_VERSION);
}

@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
this.db = db;

db.execSQL("CREATE TABLE " + TABLE_NAME
+ " (_id INTEGER PRIMARY KEY AUTOINCREMENT, "
+ A_EXPRESSION + " TEXT) ");
}

@Override
public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {
// TODO Auto-generated method stub

}

}

main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" android:gravity="center_horizontal">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Калькулятор от Андрюхи" />

<EditText
android:id="@+id/editText1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:ems="10" />
<RadioGroup
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">

<RadioButton
android:id="@+id/radioButton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="/"
android:layout_weight="1"/>

<RadioButton
android:id="@+id/radioButton2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="*"
android:layout_weight="1"/>

<RadioButton
android:id="@+id/radioButton3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="+"
android:layout_weight="1"/>

<RadioButton
android:id="@+id/radioButton4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="-"
android:layout_weight="1"/>
</RadioGroup>

<EditText
android:id="@+id/editText2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10" >


<requestFocus />

</EditText>
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Посчитать" />
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical">

<ListView
android:id="@+id/lvHistory"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
</ListView>

</LinearLayout>

</LinearLayout>

вообщем такая проблема при запуске на AVD приложение сразу же вылетает с надписью:
The application CalcbyAndrew has stoped unexpectedly. Please try again
Что тут делать? может в коде ошибка?(на скрине есть сама ошибка)
Вложения
1.jpg
1.jpg (41.87 КБ) 4115 просмотров

Аватара пользователя
Foenix
Сообщения: 4201
Зарегистрирован: 20 окт 2012, 12:01

Re: Ребят кому не лень помогите с поиском ошибок

Сообщение Foenix » 18 фев 2014, 21:50

почитай другие темы, код оформи, в лог посмотри - там все ошибки написаны.. если бы ты хотя бы пару тем почтиал самых последних понял бы, что по твоему скриншоту никто гадать не будет.
R.id.team

NullPointerException - что делать???
viewtopic.php?f=33&t=3899&p=28952#p28952
Где моя ошибка?
viewtopic.php?f=60&t=3198

Аватара пользователя
Mikhail_dev
Сообщения: 2386
Зарегистрирован: 09 янв 2012, 14:45
Откуда: Самара

Re: Ребят кому не лень помогите с поиском ошибок

Сообщение Mikhail_dev » 19 фев 2014, 11:42

Советую посмотреть вебинар "Вебинар 6. Аптечка хорошего разработчика. DDMS. Часть 1", где вначале рассказывается как находить ошибку. Данный скриншот - не ошибка.
И да, оформите код.

iandryxa
Сообщения: 58
Зарегистрирован: 23 янв 2014, 20:40

Сообщение iandryxa » 19 фев 2014, 16:24

Ок спасибо, говорю же я пока только начинающий так что не судите особо строго)

Þunarr
Сообщения: 10
Зарегистрирован: 04 апр 2016, 09:39

Re: Ребят кому не лень помогите с поиском ошибок

Сообщение Þunarr » 04 апр 2016, 10:36

У Тебя скорее всего ошибка в формировании и использовании SQLite!
Когда-то тоже с подобным возился очень долго.
Пересмотри весь код и используй логирование, без этого в БД нечего делать!

Ответить