Unfortunately, Organitza't (my app) has stopped - java

I am getting error message when I start another activity named Task. The application have 4 image buttons (the other buttons image open correctly. When I click "TaskViewer"(ImageButton2) appears the error.
The activity that attempts to open: (ViewTask)
public class ViewTask extends Activity {
protected TaskerDbHelper db;
List<Task> list;
MyAdapter adapt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_task);
db = new TaskerDbHelper(this);
list = db.getAllTasks();
adapt = new MyAdapter(this, R.layout.list_inner_view, list);
ListView listTask = (ListView) findViewById(R.id.listView1);
listTask.setAdapter(adapt);
}
public void addTaskNow(View v) {
EditText t = (EditText) findViewById(R.id.editText1);
String s = t.getText().toString();
if (s.equalsIgnoreCase("")) {
Toast.makeText(this, "enter the task description first!!",
Toast.LENGTH_LONG);
} else {
Task task = new Task(s, 0);
db.addTask(task);
Log.d("tasker", "data added");
t.setText("");
adapt.add(task);
adapt.notifyDataSetChanged();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_view_task, menu);
return true;
}
private class MyAdapter extends ArrayAdapter<Task> {
Context context;
List<Task> taskList = new ArrayList<Task>();
int layoutResourceId;
public MyAdapter(Context context, int layoutResourceId,
List<Task> objects) {
super(context, layoutResourceId, objects);
this.layoutResourceId = layoutResourceId;
this.taskList = objects;
this.context = context;
}
/**
* This method will DEFINe what the view inside the list view will
* finally look like Here we are going to code that the checkbox state
* is the status of task and check box text is the task name
*/
#Override
public View getView(int position, View convertView, ViewGroup parent) {
CheckBox chk = null;
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.list_inner_view,
parent, false);
chk = (CheckBox) convertView.findViewById(R.id.chkStatus);
convertView.setTag(chk);
chk.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
CheckBox cb = (CheckBox) v;
Task changeTask = (Task) cb.getTag();
changeTask.setStatus(cb.isChecked() == true ? 1 : 0);
db.updateTask(changeTask);
Toast.makeText(
getApplicationContext(),
"Clicked on Checkbox: " + cb.getText() + " is "
+ cb.isChecked(), Toast.LENGTH_LONG)
.show();
}
});
} else {
chk = (CheckBox) convertView.getTag();
}
Task current = taskList.get(position);
chk.setText(current.getTaskName());
chk.setChecked(current.getStatus() == 1 ? true : false);
chk.setTag(current);
Log.d("listener", String.valueOf(current.getId()));
return convertView;
}
}
}
The main activity:
public class MainActivity extends Activity {
private Context activity;
#Override
protected void onCreate (Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
entrarboton();
}
private void entrarboton() {
ImageButton accionentrar = (ImageButton) findViewById(R.id.imageButton0);
accionentrar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent LaunchIntent = getPackageManager().getLaunchIntentForPackage("com.android.calendar");
startActivity(LaunchIntent);
}
});
ImageButton accionentrar2 = (ImageButton) findViewById(R.id.imageButton3);
accionentrar2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(MainActivity.this,Notes.class));
}
});
ImageButton accionentrar3 = (ImageButton) findViewById(R.id.imageButton2);
accionentrar3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(MainActivity.this,ViewTask.class));
}
});
ImageButton accionentrar4 = (ImageButton) findViewById(R.id.imageButton4);
accionentrar4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(MainActivity.this,Altres.class));
}
});
AutoCompleteTextView auto = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView);
String[] noms = getResources() . getStringArray(R.array.noms_array);
ArrayAdapter<String> adapter;
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, noms);
auto.setThreshold(1);
auto.setAdapter(adapter);
}
}
Android Manifest:
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.dppalvaplicacio.app.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.dppalvaplicacio.app.Calendari"
android:label="#string/title_activity_calendari" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity
android:name="com.dppalvaplicacio.app.Notes"
android:label="#string/title_activity_notes" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity
android:name="com.dppalvaplicacio.app.ViewTask"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity
android:name="com.dppalvaplicacio.app.Altres"
android:label="#string/title_activity_altres" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
</application>
Logcat
Caused by: java.lang.IllegalStateException: attempt to re-open an already-closed object: SQLiteDatabase: /data/data/com.dppalvaplicacio.app/databases/taskerManager
at android.database.sqlite.SQLiteClosable.acquireReference(SQLiteClosable.java:55)
at android.database.sqlite.SQLiteDatabase.endTransaction(SQLiteDatabase.java:520)
at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:263)
at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:164)
at com.dppalvaplicacio.app.TaskerDbHelper.getAllTasks(TaskerDbHelper.java:70)
at com.dppalvaplicacio.app.ViewTask.onCreate(ViewTask.java:33)
at android.app.Activity.performCreate(Activity.java:5008)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
at android.app.ActivityThread.access$600(ActivityThread.java:130)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4745)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
TaskDbHelper
public class TaskerDbHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "taskerManager";
// tasks table name
private static final String TABLE_TASKS = "tasks";
// tasks Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_TASKNAME = "taskName";
private static final String KEY_STATUS = "status";
public TaskerDbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String sql = "CREATE TABLE IF NOT EXISTS " + TABLE_TASKS + " ( "
+ KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + KEY_TASKNAME
+ " TEXT, " + KEY_STATUS + " INTEGER)";
db.execSQL(sql);
db.close();
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldV, int newV) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_TASKS);
// Create tables again
onCreate(db);
}
// Adding new task
public void addTask(Task task) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_TASKNAME, task.getTaskName()); // task name
// status of task- can be 0 for not done and 1 for done
values.put(KEY_STATUS, task.getStatus());
// Inserting Row
db.insert(TABLE_TASKS, null, values);
db.close(); // Closing database connection
}
public List<Task> getAllTasks() {
List<Task> taskList = new ArrayList<Task>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_TASKS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Task task = new Task();
task.setId(cursor.getInt(0));
task.setTaskName(cursor.getString(1));
task.setStatus(cursor.getInt(2));
// Adding contact to list
taskList.add(task);
} while (cursor.moveToNext());
}
// return task list
return taskList;
}
public void updateTask(Task task) {
// updating row
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_TASKNAME, task.getTaskName());
values.put(KEY_STATUS, task.getStatus());
db.update(TABLE_TASKS, values, KEY_ID + " = ?",new String[] {String.valueOf(task.getId())});
db.close();
}
}

The problem is in your TaskDBHelper class, and more specifically the onCreate method. This method is called automatically when you try to do work on the database, but the database is not created yet. So it first calls the onCreate method and then the method, that does work on it, in your case - getAllTasks. The problem is that you are closing your db in the onCreate method, preventing any further operations on the database within this class instance. Your method should look like this:
public void onCreate(SQLiteDatabase db) {
String sql = "CREATE TABLE IF NOT EXISTS " + TABLE_TASKS + " ( "
+ KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + KEY_TASKNAME
+ " TEXT, " + KEY_STATUS + " INTEGER)";
db.execSQL(sql);
}

Related

How can I save my listview with Saved Preferences

I want develop Pomodoro app. I have edittext, countdowntimer, listview on my project. My app can work.And I have a lot of text on my list. my 3. countdown timer on finish I add text my listview. How can I save listview with sharedpreferences? and How Can I do this . Thanks A lot of
main_activty.class
public class pomodoro extends AppCompatActivity {
Button baslat,backhome,bitir;
EditText edittextcalisma,edittextmola;
CountDownTimer calisma,mola;
ArrayList<String> list = new ArrayList<String>();
ArrayAdapter arrayAdapter;
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pomodoro);
listView=(ListView)findViewById(R.id.listv);
arrayAdapter = new ArrayAdapter<String>(
this,R.layout.list_view,R.id.textitem, list);
listView.setAdapter(arrayAdapter);
bitir=findViewById(R.id.bitirbutton);
baslat = findViewById(R.id.baslatbutton);
edittextcalisma = findViewById(R.id.edittextcalisma);
edittextmola = findViewById(R.id.edittextmola);
baslat.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
closeKeyboard();
final int molapo = Integer.valueOf(edittextmola.getText().toString());
final int calismapo = Integer.valueOf(edittextcalisma.getText().toString());
if (calismapo <= 600 && molapo <= 600 && calismapo > 0 && molapo>0){
calisma = new CountDownTimer(calismapo * 60000, 1000) {
#Override
public void onTick(long millis) {
}
#Override
public void onFinish() {
final int molapo = Integer.valueOf(edittextmola.getText().toString());
mola = new CountDownTimer(molapo * 60000, 1000) {
#Override
public void onTick(long millis) {
}
#Override
public void onFinish() {
pomodoro.setText("Bitti");
CountDownTimer bekle = new CountDownTimer(5000, 1000) {
#Override
public void onTick(long millis) {
}
#Override
public void onFinish() {
Calendar c = Calendar.getInstance();
SimpleDateFormat dateformat = new SimpleDateFormat("dd-MMMM-yyyy HH:mm");
String datetime = dateformat.format(c.getTime());
list.add("Çalışma Süresi : " + calismapo +" dk "+"\n"+ "Mola Süresi : " + molapo+" dk " +"\n" + datetime);
arrayAdapter.notifyDataSetChanged();
}
}.start();
}
}.start();
}
}.start();
}
}
});
}
}
you need to put metadata in LUNCHER activity in order to work
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<meta-data android:name="android.app.shortcuts"
android:resource="#xml/shortcuts" />
</activity>

Neither handleIntent nor onCreate being called in Searchable Activity

I know there are many questions like this on here, and I have looked at many of them, like this one and all of the questions it references, but I still have no solution. The problem is that I have followed the Android Developer guide on using the search widget, but when I open my app and hit the search widget, the onNewIntent method never gets called. I put a Log.e into the handleIntent method so I could check if everything was connecting before I moved on to the next part of the function, but it never gets called. I thought the issue might be in the MainActivity in the onCreateOptionsMenu, if maybe I'm not calling something right there. This is my first time trying to do this, and I'd really appreciate any kind of help on this issue, thanks.
Here is my SearchableActivity:
package com.gmd.referenceapplication;
import android.app.ListActivity;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ListView;
import android.widget.Toast;
public class SearchableActivity extends ListActivity {
DatabaseTable db= new DatabaseTable(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_searchable);
// get the intent sent when user searches from search widget, verify the action and extract what is typed in
Intent intent = getIntent();
handleIntent(intent);
}
public void onNewIntent(Intent intent) {
setIntent(intent);
handleIntent(intent);
}
private void handleIntent(Intent intent) {
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
String query = intent.getStringExtra(SearchManager.QUERY);
Cursor c = db.getWordMatches(query, null);
Log.e("Search Operation", "Database searched");
System.out.println(R.string.app_name);
//still need to process Cursor and display results
}
}
public void onListItemClick(ListView l,
View v, int position, long id) {
// call detail activity for clicked entry
}
private void doSearch(String queryStr) {
// get a Cursor, prepare the ListAdapter
// and set it
}
}
Android Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
package="com.gmd.referenceapplication">
<application
android:allowBackup="true"
android:icon="#mipmap/nist_logo"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/Theme.AppCompat.Light.NoActionBar">
<meta-data
android:name="android.app.default_searchable"
android:value="com.example.SearchActivity" />
<!-- main activity below, will be a home screen -->
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<!-- //the physical constants overview page, will hopefully split into smaller categories -->
<activity
android:name=".FundamentalPhysicalConstants"
android:label="#string/app_name" />
<!-- searchable activity, performs searches and presents results -->
<activity android:name=".SearchableActivity">
<intent-filter>
<action android:name="android.intent.action.SEARCH" />
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<meta-data
android:name="android.app.searchable"
android:resource="#xml/searchable" />
</activity>
<provider
android:name=".ConstantSuggestionProvider"
android:authorities="query"
android:enabled="true"
android:exported="true" />
<activity android:name=".ExampleListView" />
<activity android:name=".CommonConstants" />
<activity android:name=".ElectromagneticConstants" />
<activity android:name=".AtomicNuclearConstants" />
<activity android:name=".PhysicoChemicalConstants" />
<activity android:name=".ReferenceLinks" />
<activity android:name=".SIBaseUnits"/>
</application>
</manifest>
Searchable xml:
<?xml version="1.0" encoding="utf-8"?>
<searchable xmlns:android="http://schemas.android.com/apk/res/android"
android:label="#string/app_name"
android:hint="#string/search_hint">
</searchable>
Database Table:
package com.gmd.referenceapplication;
import android.content.ContentValues;
import android.content.Context;
import android.content.res.Resources;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.text.TextUtils;
import android.util.Log;
import com.gmd.referenceapplication.R;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
/**
* Created by gmd on 6/8/2016.
*/
public class DatabaseTable {
public static final String TAG = "ConstantDatabase";
//the columns included in the table
public static final String COL_QUANTITY = "QUANTIY";
public static final String COL_VALUE = "VALUE";
public static final String COL_UNCERTAINTY = "UNCERTAINTY";
public static final String COL_UNIT = "UNIT";
private static final String DATABASE_NAME = "CONSTANTS";
private static final String FTS_VIRTUAL_TABLE = "FTS";
private static final int DATABASE_VERSION = 1;
private final DatabaseOpenHelper mDatabaseOpenHelper;
public DatabaseTable(Context context){
mDatabaseOpenHelper = new DatabaseOpenHelper(context);
}
private static class DatabaseOpenHelper extends SQLiteOpenHelper {
private final Context mHelperContext;
private SQLiteDatabase mDatabase;
private static final String FTS_TABLE_CREATE =
"CREATE VIRTUAL TABLE " + FTS_VIRTUAL_TABLE +
" USING fts3 (" +
COL_QUANTITY + ", " +
COL_VALUE + "," +
COL_UNCERTAINTY + "," +
COL_UNIT + ")";
public DatabaseOpenHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
Log.e("Database Operation", "Database Created / Opened...");
mHelperContext = context;
}
#Override
public void onCreate(SQLiteDatabase db) {
mDatabase = db;
mDatabase.execSQL(FTS_TABLE_CREATE);
Log.e("Database Operation", "Constants Table Created ...");
loadConstants();
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS " + FTS_VIRTUAL_TABLE);
onCreate(db);
}
// populating the virtual table with a string reading code
private void loadConstants() {
new Thread(new Runnable() {
public void run() {
try {
loadConstantss();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}).start();
Log.e("Loading", "Constants Table Populated ...");
}
private void loadConstantss() throws IOException {
final Resources resources = mHelperContext.getResources();
InputStream inputStream = resources.openRawResource(R.raw.txt);
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
try {
String line;
while ((line = reader.readLine()) != null) {
String[] strings = TextUtils.split(line, ",");
if (strings.length < 4) continue;
long id = addConstant(strings[0].trim(), strings[1].trim(), strings[2].trim(), strings[3].trim());
if (id < 0) {
Log.e(TAG, "unable to add word: " + strings[0].trim());
}
}
} finally {
reader.close();
}
}
public long addConstant(String quantity, String value, String uncertainty, String unit) {
ContentValues initialValues = new ContentValues();
initialValues.put(COL_QUANTITY, quantity);
initialValues.put(COL_VALUE, value);
initialValues.put(COL_UNCERTAINTY, uncertainty);
initialValues.put(COL_UNIT, unit);
return mDatabase.insert(FTS_VIRTUAL_TABLE, null, initialValues);
}
}
public Cursor getWordMatches(String query, String[] columns) {
String selection = COL_QUANTITY + " MATCH ?";
String[] selectionArgs = new String[] {query+"*"};
return query(selection, selectionArgs, columns);
}
public Cursor query(String selection, String[] selectionArgs, String[] columns) {
SQLiteQueryBuilder builder = new SQLiteQueryBuilder();
builder.setTables(FTS_VIRTUAL_TABLE);
Cursor cursor = builder.query(mDatabaseOpenHelper.getReadableDatabase(),
columns, selection, selectionArgs, null, null, null);
if (cursor == null) {
return null;
} else if (!cursor.moveToFirst()) {
cursor.close();
return null;
}
return cursor;
}
}
MainActivity:
package com.gmd.referenceapplication;
import android.app.SearchManager;
import android.app.SearchableInfo;
import android.content.Context;
import android.content.Intent;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.SearchView.OnQueryTextListener;
import android.support.v7.widget.SearchView;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.support.v7.widget.SearchView;
public class MainActivity extends AppCompatActivity {
DatabaseTable dbHelper = new DatabaseTable(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar myToolbar = (Toolbar) findViewById(R.id.my_toolbar);
setSupportActionBar(myToolbar);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.overflow, menu);
SearchView searchView = (SearchView) menu.findItem(R.id.search).getActionView();
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
//search button is pressed
dbHelper.getWordMatches(query,null);
return true;
}
#Override
public boolean onQueryTextChange(String newText) {
// User changed the text
return true;
}
});
SearchManager searchManager =
(SearchManager) getSystemService(Context.SEARCH_SERVICE);
searchView =
(SearchView) menu.findItem(R.id.search).getActionView();
searchView.setSearchableInfo(
searchManager.getSearchableInfo(getComponentName()));
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.constants:
startActivity(new Intent(MainActivity.this, FundamentalPhysicalConstants.class));
return true;
case R.id.joes_rules:
//go to rules
//startActivity(new Intent(MainActivity.this, ExampleListView.class));
return true;
case R.id.home:
//Go back to the home screen
return true;
case R.id.search:
//open search
return true;
case R.id.links:
//go to referencelinks
startActivity(new Intent(this, ReferenceLinks.class));
return true;
case R.id.base_units:
//go to baseunits
startActivity(new Intent(this, SIBaseUnits.class));
return true;
default:
// If we got here, the user's action was not recognized.
// Invoke the superclass to handle it.
return super.onOptionsItemSelected(item);
}
}
}

Unknown URI when trying to edit/update sqlite database records

Here are is the logcat:
06-24 13:33:04.226 23618-23618/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.saleh.findmypassword, PID: 23618
java.lang.IllegalArgumentException: Unknown Uri: content://com.example.saleh.findmypassword.provider/PInfos/1
at com.example.saleh.findmypassword.PInfoProvider.update(PInfoProvider.java:161)
at android.content.ContentProvider$Transport.update(ContentProvider.java:287)
at android.content.ContentResolver.update(ContentResolver.java:1316)
at com.example.saleh.findmypassword.EditActivity$1.onClick(EditActivity.java:62)
at android.view.View.performClick(View.java:4438)
at android.view.View$PerformClick.run(View.java:18422)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5001)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
Content Provider class:
public class PInfoProvider extends ContentProvider {
private PInfoDatabase mOpenHelper;
private static String TAG = PInfoProvider.class.getSimpleName();
private static final UriMatcher sUriMatcher = buildUriMatcher();
private static final int PINFOS = 100;
private static final int PINFOS_ID = 101;
private static UriMatcher buildUriMatcher(){
final UriMatcher matcher = new UriMatcher(UriMatcher.NO_MATCH);
final String authority = PInfoContract.CONTENT_AUTHORITY;
matcher.addURI(authority, "PInfos", PINFOS);
matcher.addURI(authority, "Pinfos/*", PINFOS_ID);
return matcher;
}
#Override
public boolean onCreate() {
mOpenHelper = new PInfoDatabase(getContext());
return true;
}
private void deleteDatabase(){
mOpenHelper.close();
PInfoDatabase.deleteDatabase(getContext());
mOpenHelper = new PInfoDatabase(getContext());
}
#Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
final SQLiteDatabase db = mOpenHelper.getReadableDatabase();
final int match = sUriMatcher.match(uri);
SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
queryBuilder.setTables(PInfoDatabase.Tables.PINFOS);
switch(match){
case PINFOS:
//do nothing
break;
case PINFOS_ID:
String id = PInfoContract.PInfos.getPInfoId(uri);
queryBuilder.appendWhere(BaseColumns._ID + "=" + id);
break;
default:
throw new IllegalArgumentException("Unknown Uri: " + uri);
}
Cursor cursor = queryBuilder.query(db, projection, selection, selectionArgs, null, null, sortOrder);
//projection in content provider means the list of columns you want to return.
return cursor;
}
#Override
public String getType(Uri uri) {
final int match = sUriMatcher.match(uri);
switch(match){
case PINFOS:
return PInfoContract.PInfos.CONTENT_TYPE;
case PINFOS_ID:
return PInfoContract.PInfos.CONTENT_ITEM_TYPE;
default:
throw new IllegalArgumentException("Unknown Uri: " + uri);
}
}
#Override
public Uri insert(Uri uri, ContentValues values) {
//ContentValues: is a list of content values of our database such as the email and username. Contains the column names and the values we want to associate to it when we're writing to the database/
Log.v(TAG, "insert(uri=" + uri + ", values =" + values.toString());
final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
final int match = sUriMatcher.match(uri);
switch(match){
case PINFOS: //only using the PInfo and not the ID because it's to insert only.
long recordID = db.insertOrThrow(PInfoDatabase.Tables.PINFOS, null, values); //inserts a row into the database
return PInfoContract.PInfos.buildPInfoUri(String.valueOf(recordID));
default:
throw new IllegalArgumentException("Unknown Uri: " + uri);
}
}
#Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
Log.v(TAG, "delete(uri=" + uri);
if(uri.equals(PInfoContract.URI_TABLE)){
deleteDatabase();
return 0;
//This will be executed if the user didn't input a valid record id.
//Base content uri doesn't contain an ID nor a path.
}
final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
final int match = sUriMatcher.match(uri);
String selectionCriteria = selection;
switch(match){
/*
case PInfo:
If this was called and didn't "break" it would change all the records in the table.
We will still leave it out because we added the database deletion code above.
break;
*/
case PINFOS_ID:
String id = PInfoContract.PInfos.getPInfoId(uri);
selectionCriteria = BaseColumns._ID + "=" + id
+ (!TextUtils.isEmpty(selection) ? "AND (" + selection + ")" : "");
return db.delete(PInfoDatabase.Tables.PINFOS, selectionCriteria, selectionArgs);
default:
throw new IllegalArgumentException("Unknown Uri: " + uri);
}
}
#Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
Log.v(TAG, "update(uri=" + uri + ", values =" + values.toString());
final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
final int match = sUriMatcher.match(uri);
String selectionCriteria = selection;
//We set selectionCriteria to equal selection in the case PInfo case was chosen. After all,
//we still need to record the selection.
switch(match){
case PINFOS:
//do nothing
//If this was called and didn't "break" it would change all the records in the table.
break;
case PINFOS_ID:
String id = PInfoContract.PInfos.getPInfoId(uri);
selectionCriteria = BaseColumns._ID + "=" + id
+ (!TextUtils.isEmpty(selection) ? "AND (" + selection + ")" : "");
break;
default:
throw new IllegalArgumentException("Unknown Uri: " + uri);
}
return db.update(PInfoDatabase.Tables.PINFOS, values, selectionCriteria, selectionArgs);
}
}
EditActivity class:
public class EditActivity extends FragmentActivity {
private final String LOG_TAG = EditActivity.class.getSimpleName();
private TextView mWebsiteTextView, mEmailTextView, mUsernameTextView, mPasswordTextView;
private Button mButton;
private ContentResolver mContentResolver;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_edit); //same layout as the AddActivity class.
getActionBar().setDisplayHomeAsUpEnabled(true); //returns up one level rather than back to the top level
mWebsiteTextView = (TextView) findViewById(R.id.pinfoWebsite);
mEmailTextView = (TextView) findViewById(R.id.pinfoEmail);
mUsernameTextView = (TextView) findViewById(R.id.pinfoUsername);
mPasswordTextView = (TextView) findViewById((R.id.pinfoPassword));
mContentResolver = EditActivity.this.getContentResolver();
Intent intent = getIntent(); //Getting the intent that was passed to this activity from the PInfoCustomAdapter class
final String _id = intent.getStringExtra(PInfoContract.PInfoColumns.PINFO_ID);
String website = intent.getStringExtra(PInfoContract.PInfoColumns.PINFO_WEBSITE);
String email = intent.getStringExtra(PInfoContract.PInfoColumns.PINFO_EMAIL);
String username= intent.getStringExtra(PInfoContract.PInfoColumns.PINFO_USERNAME);
String password = intent.getStringExtra(PInfoContract.PInfoColumns.PINFO_PASSWORD);
//Now to populate what's on screen:
mWebsiteTextView.setText(website);
mEmailTextView.setText(email);
mUsernameTextView.setText(username);
mPasswordTextView.setText(password);
mButton = (Button) findViewById(R.id.saveButton);
mButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ContentValues values = new ContentValues(); //Content Values Class is used to store a set of values that the ContentResolver can process.
values.put(PInfoContract.PInfoColumns.PINFO_WEBSITE, mWebsiteTextView.getText().toString()); //.put add values ot the set & .toString() to convert it to the right format
values.put(PInfoContract.PInfoColumns.PINFO_EMAIL, mEmailTextView.getText().toString());
values.put(PInfoContract.PInfoColumns.PINFO_USERNAME, mUsernameTextView.getText().toString());
values.put(PInfoContract.PInfoColumns.PINFO_PASSWORD, mPasswordTextView.getText().toString());
Uri uri = PInfoContract.PInfos.buildPInfoUri(_id); //To know which record we're dealing with
int recordsUpdated = mContentResolver.update(uri, values, null, null);
Log.d(LOG_TAG, "Number of records updated = " + recordsUpdated);
Intent intent = new Intent(EditActivity.this, MainActivity.class);
startActivity(intent);
finish(); //always use this when the activity's process is finished
}
});
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this); //Just allows to navigate back to the parent method. So: when someone presses home it will go back to the kain menu
break;
}
return true;
}
}
The class where the uri is being created:
public class PInfoContract {
interface PInfoColumns {
String PINFO_ID = "_id";
String PINFO_WEBSITE = "PInfo_Website";
String PINFO_EMAIL = "PInfo_Email";
String PINFO_USERNAME = "PInfo_Username";
String PINFO_PASSWORD = "PInfo_Password";
}
public static final String CONTENT_AUTHORITY = "com.example.saleh.findmypassword.provider";
public static final Uri BASE_CONTENT_URI = Uri.parse("content://" + CONTENT_AUTHORITY);
public static final String PATH_PINFOS = "PInfos";
public static final Uri URI_TABLE = Uri.parse(BASE_CONTENT_URI.toString() + "/" + PATH_PINFOS);
public static final String[] TOP_LEVEL_PATHS = {
PATH_PINFOS
};
public static class PInfos implements PInfoColumns, BaseColumns {
public static final Uri CONTENT_URI =
BASE_CONTENT_URI.buildUpon().appendEncodedPath(PATH_PINFOS).build();
public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd." + CONTENT_AUTHORITY + ".PInfos";
public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd." + CONTENT_AUTHORITY + ".PInfos";
public static Uri buildPInfoUri(String pinfoid) {
return CONTENT_URI.buildUpon().appendEncodedPath(pinfoid).build();
}
public static String getPInfoId(Uri uri) {
return uri.getPathSegments().get(1);
}
}
}
The manifest:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.saleh.findmypassword">
<permission android:name="com.example.saleh.findmypassword.provider.READWRITE" />
<uses-permission android:name="com.example.saleh.findmypassword.provider.READWRITE" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#android:style/Theme.WithActionBar">
<activity
android:name=".MainActivity"
android:label="Personal Info">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".AddActivity"
android:label="#string/add_pinfo_title"
android:parentActivityName=".MainActivity"
android:noHistory="true"/>
<activity
android:name=".EditActivity"
android:label="#string/edit_pinfo_title"
android:parentActivityName="com.example.saleh.findmypassword.MainActivity"
android:noHistory="true"/>
<activity
android:name=".SearchActivity"
android:label="#string/search_pinfo_title"
android:parentActivityName=".MainActivity"
android:noHistory="true"/>
<provider
android:name="com.example.saleh.findmypassword.PInfoProvider"
android:authorities="com.example.saleh.findmypassword.provider"
android:exported="true"
android:readPermission="com.example.saleh.findmypassword.provider.READWRITE"
android:writePermission="com.example.saleh.findmypassword.provider.READWRITE" />
</application>
</manifest>
Your UriMatcher is matching any text "Pinfos/*", and it should match any number "Pinfos/#"
docs

IllegalArgumentException: Unknown URL content:// CONTENT

IllegalArgumentException: Unknown URL content://
^ Having a nightmare with the above. I've checked my variables and paths but can't see what the issue is? Greatly appreciate any pointers!
Here's my trace.
java.lang.IllegalArgumentException: Unknown URL
content://com.purewowstudio.topmovies.data.FilmProvider/film_data
at android.content.ContentResolver.insert(ContentResolver.java:1203)
at com.purewowstudio.topmovies.data.DatabaseHelper.addFilm(DatabaseHelper.java:52)
at com.purewowstudio.topmovies.fragments.FilmList$getFilms.onPostExecute(FilmList.java:72)
at com.purewowstudio.topmovies.fragments.FilmList$getFilms.onPostExecute(FilmList.java:62)
at android.os.AsyncTask.finish(AsyncTask.java:632)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5262)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:898)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:693)
Content Provider
public class FilmProvider extends ContentProvider {
public static final String TABLE_NAME = "film_data";
public static final String AUTHORITY = "com.purewowstudio.topmovies.data.FilmProvider";
public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/" + TABLE_NAME);
public static final int FILMS = 1;
public static final int FILMS_ID = 2;
public static final UriMatcher sURIMatcher =
new UriMatcher(UriMatcher.NO_MATCH);
static {
sURIMatcher.addURI(AUTHORITY, TABLE_NAME, FILMS);
sURIMatcher.addURI(AUTHORITY, TABLE_NAME + "/#",
FILMS_ID);
}
private DatabaseHelper mDB;
public boolean onCreate() {
mDB = new DatabaseHelper(getContext(), null, null, 1);
return false;
}
#Override
public String getType(Uri uri) {
return null;
}
#Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
queryBuilder.setTables(MovieDataContract.TABLE_NAME);
int uriType = sURIMatcher.match(uri);
switch (uriType) {
case FILMS_ID:
queryBuilder.appendWhere(MovieDataContract.FilmEntry._ID + "="
+ uri.getLastPathSegment());
break;
case FILMS:
break;
default:
throw new IllegalArgumentException("Unknown URI");
}
Cursor cursor = queryBuilder.query(mDB.getReadableDatabase(),
projection, selection, selectionArgs, null, null,
sortOrder);
cursor.setNotificationUri(getContext().getContentResolver(),
uri);
return cursor;
}
#Override
public Uri insert(Uri uri, ContentValues values) {
int uriType = sURIMatcher.match(uri);
SQLiteDatabase sqlDB = mDB.getWritableDatabase();
long id = 0;
switch (uriType) {
case FILMS:
id = sqlDB.insert(MovieDataContract.TABLE_NAME,
null, values);
break;
default:
throw new IllegalArgumentException("Unknown URI: "
+ uri);
}
getContext().getContentResolver().notifyChange(uri, null);
return Uri.parse(MovieDataContract.TABLE_NAME + "/" + id);
}
DatabaseHelper Class
public class DatabaseHelper extends SQLiteOpenHelper {
private ContentResolver myCR;
public DatabaseHelper(Context context, String name,
SQLiteDatabase.CursorFactory factory, int version) {
super(context, MovieDataContract.DATABASE_NAME, factory, MovieDataContract.DATABASE_VERSION);
myCR = context.getContentResolver();
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(MovieDataContract.FilmEntry.SQL_CREATE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL(MovieDataContract.FilmEntry.DELETE_TABLE);
onCreate(db);
}
public void addFilm(Film film){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(MovieDataContract.FilmEntry.COLUMN_FILM_TITLE, film.getTitle());
values.put(MovieDataContract.FilmEntry.COLUMN_FILM_RATING, film.getRating());
values.put(MovieDataContract.FilmEntry.COLUMN_FILM_RUNTIME, film.getRuntime());
values.put(MovieDataContract.FilmEntry.COLUMN_FILM_CRITICS, film.getCritics());
values.put(MovieDataContract.FilmEntry.COLUMN_FILM_AUDIENCE, film.getAudience());
values.put(MovieDataContract.FilmEntry.COLUMN_FILM_SYNOPSIS, film.getSynopsis());
values.put(MovieDataContract.FilmEntry.COLUMN_FILM_PROFILE, film.getProfile());
myCR.insert(FilmProvider.CONTENT_URI, values);
db.insert(MovieDataContract.TABLE_NAME,
null,
values);
db.close();
}
Manifest
<?xml version="1.0" encoding="utf-8"?>
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/TopMoviesTheme" >
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".DetailFragment"
android:label="#string/title_activity_detail_fragment"
android:parentActivityName=".MainActivity" >
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.purewowstudio.topmovies.MainActivity" />
<provider
android:name=".data.filmProvider"
android:authorities="com.purewowstudio.topmovies.data.filmProvider"
android:exported="true">
</provider>
</activity>
</application>
</manifest>
First, move <provider> to be a child of <application>, not <activity>.
Second, change android:exported="true" to android:exported="false", until such time as you secure your ContentProvider. As it stands, once you fix the <provider> element location as noted above, any app can read and write anything in your provider, which is unlikely to be what the user wants.
I have added package name in authorities.that's why I got this issue.I have to add Provider name in authorities.
<provider
android:name="LoginContentProvider"
android:authorities="com.provider.name.team"
android:exported="false" />

android: saving json to sqlite

i'm a new bie in android and java i want to save a table from sql server(external database) to sqlite(internal database).
1. my json is not getting stored and every record is same like this "com.example.db_client.DeptTable#b3e4e9e0" when i opens the db file in sqlite browser. I don't understand what is this.
when i run my app i sometimes get this exception and sometimes i don't.
FATAL EXCEPTION: main
Process: com.example.db_client, PID: 1697
java.lang.IllegalArgumentException: Activity DeptActivity does not have a parent activity name specified. (Did you forget to add the android.support.PARENT_ACTIVITY element in your manifest?)
I really need help please look into my problem. thanks in advance.
code of database helper class
public class SqliteDB {
public static final String KEY_ID = "no";
public static final String KEY_NAME = "name";
private static final String TAG = "DBAdapter";
private static final String DATABASE_NAME = "SQLiteDB";
private static final String TABLE_NAME = "Department";
private static final int DATABASE_VERSION = 2;
private static final String CREATE_TABLE =
"create table departmentList (id INTEGER PRIMARY KEY, name TEXT);";
private final Context context;
private DatabaseHelper DBHelper;
private SQLiteDatabase db;
public SqliteDB(Context ctx) {
this.context = ctx;
DBHelper = new DatabaseHelper(context);
}
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
try {
db.execSQL(CREATE_TABLE);
} catch (SQLException e) {
e.printStackTrace();
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS sample");
onCreate(db);
}
}
//---open SQLite DB---
public SqliteDB open() throws SQLException {
db = DBHelper.getWritableDatabase();
return this;
}
//---close SQLite DB---
public void close() {
DBHelper.close();
}
//---insert data into SQLite DB---
public long insert(String name) {
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_NAME, name);
return db.insert(TABLE_NAME, null, initialValues);
}
//---Delete All Data from table in SQLite DB---
public void deleteAll() {
db.delete(TABLE_NAME, null, null);
}
//---Get All Contacts from table in SQLite DB---
public Cursor getAllData() {
return db.query(TABLE_NAME, new String[] {KEY_NAME},
null, null, null, null, null);
}
}
code of activity class
public class DeptActivity extends Activity{
ArrayAdapter<String> adapter;
ListView listv;
Context context;
ArrayList<String> data;
SqliteDB sqlite;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dept);
sqlite = new SqliteDB(DeptActivity.this);
setupActionBar();
data = new ArrayList<String>();
listv = (ListView) findViewById(R.id.lv_dept);
context = this;
adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, data);
listv.setAdapter(adapter);
Toast.makeText(this,"Loading Please Wait..",Toast.LENGTH_SHORT).show();
new AsyncLoadDeptDetails().execute();
}
public class AsyncLoadDeptDetails extends
AsyncTask<Void, JSONObject, ArrayList<DeptTable>> {
ArrayList<DeptTable> deptTable = null;
#Override
public ArrayList<DeptTable> doInBackground(Void... params) {
// TODO Auto-generated method stub
RestAPI api = new RestAPI();
try {
JSONObject jsonObj = api.GetDepartmentDetails();
JSONParser parser = new JSONParser();
Log.i( "department list", jsonObj.toString());
deptTable = parser.parseDepartment(jsonObj);
sqlite();
} catch (Exception e) {
}
return deptTable;
}
private void sqlite() {
// TODO Auto-generated method stub
sqlite.open();
for(int i=0; i<deptTable.size(); i++) {
sqlite.insert(deptTable.get(i).toString());
}
sqlite.close();
}
#Override
protected void onPostExecute(ArrayList<DeptTable> result) {
// TODO Auto-generated method stub
for (int i = 0; i < result.size(); i++) {
data.add(result.get(i).getNo() + " " + result.get(i).getName());
}
adapter.notifyDataSetChanged();
Toast.makeText(context,"Loading Completed",Toast.LENGTH_SHORT).show();
} }
and the table which i want to save in sqlite db looks like this.
no. name
1 engineering
2 finance
3 commerce
public class DeptTable {
int no;
String name;
public DeptTable(int no, String name) {
super();
this.no = no;
this.name = name;
}
code of deptTable Class
public DeptTable() {
super();
this.no=0;
this.name = null;
}
public int getNo() {
return no;
}
public void setNo(int no) {
this.no = no;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
code of json parser class
public class JSONParser {
public JSONParser()
{
super();
}
public ArrayList<DeptTable> parseDepartment(JSONObject object)
{
ArrayList<DeptTable> arrayList=new ArrayList<DeptTable>();
try {
JSONArray jsonArray=object.getJSONArray("Value");
JSONObject jsonObj=null;
for(int i=0;i<jsonArray.length();i++)
{
jsonObj =jsonArray.getJSONObject(i);
arrayList.add(new DeptTable(jsonObj.getInt("no"), jsonObj.getString("name")));
}
} catch (JSONException e) {
// TODO Auto-generated catch block
Log.d("JSONParser => parseDepartment", e.getMessage());
}
return arrayList;
}
public boolean parseUserAuth(JSONObject object)
{ boolean userAtuh=false;
try {
userAtuh = object.getBoolean("Value");
} catch (JSONException e) {
// TODO Auto-generated catch block
Log.d("JSONParser => parseUserAuth", e.getMessage());
}
return userAtuh; }
code of manifest
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="21" />
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.example.db_client.DeptActivity"
android:label="#string/app_name" >
</activity>
</application>
</manifest>
enter code here
If you want to use the toString method the class has to implement the toString method otherwise it will just return the default for object with you find out is not so useful. (This "com.example.db_client.DeptTable#b3e4e9e0"). To implement it just type do like this.
#Override
public String toString() {
//What you want to return here.
}
But I'm guessing you want to add some value to the database so you want to call the getter method of your class like this.
private void sqlite() {
sqlite.open();
for(int i=0; i<deptTable.size(); i++) {
sqlite.insert(deptTable.get(i).getName());
}
sqlite.close();
}
You need to add the android:parentActivityName field to DeptActivity like this.
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="21" />
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.example.db_client.DeptActivity"
android:label="#string/app_name"
android:parentActivityName=".MainActivity">
</activity>
</application>
</manifest>

Categories