Can't get Android ContentProvider to work - java

I am trying to put together a simple app to help me understand the content provider but I can't get it to work. I want to insert data into a database but I think the problem I have is somewhere with the URI.
** I am trying to follow a similar pattern as shown in the Udacity tutorials
Here is what I have
Android Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.android.simplecontentprovider">
<provider
android:authorities="com.example.android.simplecontentprovider.app"
android:name=".data.MyContentProvider" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
ContentProvider:
public class MyContentProvider extends ContentProvider {
MyDatabaseHelper mOpenHelper;
private static final int NAME = 1;
// Creates a UriMatcher object.
private static final UriMatcher sUriMatcher = buildUriMatcher();
static UriMatcher buildUriMatcher() {
final UriMatcher matcher = new UriMatcher(UriMatcher.NO_MATCH);
final String authority = MyDataContract.CONTENT_AUTHORITY; // Value = com.example.android.simplecontentprovider.app
matcher.addURI(authority, MyDataContract.PATH_TABLE, NAME); //PATH_TABLE = tblUserData
//matcher.addURI(authority, MyDataContract.PATH_TABLE + "/*", NAME);
return matcher;
}
#Override
public boolean onCreate() {
mOpenHelper = new MyDatabaseHelper(getContext());
return true;
}
#Override
public Cursor query(Uri uri, String[] strings, String s, String[] strings1, String s1) {
return null;
}
#Override
public String getType(Uri uri) {
int match = sUriMatcher.match(uri);
switch (match){
case NAME:
return MyDataContract.UserDetailsEntry.CONTENT_TYPE;
default:
throw new UnsupportedOperationException("UNKNOWN URI: " + uri);
}
}
#Override
public Uri insert(Uri uri, ContentValues contentValues) {
final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
final int match = sUriMatcher.match(uri);
Uri returnUri;
switch (match) {
case NAME: {
long _id = db.insert(MyDataContract.UserDetailsEntry.TABLE_NAME, null, contentValues);
if ( _id > 0 )
returnUri = MyDataContract.UserDetailsEntry.buildtblUserDetailsUri(_id);
else
throw new android.database.SQLException("Failed to insert row into " + uri);
break;
}
default:
throw new UnsupportedOperationException("Unknown uri: " + uri);
}
getContext().getContentResolver().notifyChange(uri, null);
return returnUri;
}
#Override
public int delete(Uri uri, String s, String[] strings) {
return 0;
}
#Override
public int update(Uri uri, ContentValues contentValues, String s, String[] strings) {
return 0;
}
}
and finally the MainActivity
ContentResolver resolver = getContentResolver();
Uri uri = MyDataContract.UserDetailsEntry.buildtblUserDetailsAll("MyTestName");
Log.e("RESOLVER URI: ", uri.toString());
ContentValues values = new ContentValues();
values.put(MyDataContract.UserDetailsEntry.COLUMN_NAME, "MyTestName");
try {
resolver.insert(uri, values);
}catch (Exception e){
Log.e("RESOLVER INSERT: ", e.toString());
}
When I run it through the debugger I get this message:
java.lang.IllegalArgumentException: Unknown URL content://com.example.android.simplecontentprovider.app/tblUserData/MyTestName
this is the default value for the insert in the content provider. I am not sure if I am missing the authority part

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.android.simplecontentprovider">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<provider
android:authorities="com.example.android.simplecontentprovider.app"
android:name=".data.MyContentProvider" />
</application>
</manifest>

Related

I don't know why i am still getting "android.os.NetworkOnMainThreadException" error, while using AsyncTask [duplicate]

This question already has answers here:
NetworkOnMainThreadException [duplicate]
(5 answers)
Closed 4 years ago.
I am new to android programming and i am trying to get my head around the AsyncTask concept so please review this code and tell me why it is crashing and keeps giving the "android.os.NetworkOnMainThreadException" error.
This app just tells the weather according to the given x and y coordinates using a bit web scraping.
Here is my code:
public class MainActivity extends AppCompatActivity {
TextView weatherInfo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
weatherInfo = (TextView) findViewById(R.id.weather_info);
Weathers runner = new Weathers();
String GetInfo = runner.doInBackground();
weatherInfo.append(GetInfo);
}
}
class Weathers extends AsyncTask<String,String,String>{
#Override
protected String doInBackground(String... strings) {
String x="19.11";
String y="72.88";
String result = null;
try {
Document doc = Jsoup.connect("https://weather.com/en-IN/weather/today/l/"+x+","+y).get();
for (Element row : doc.select("header[class=loc-container]") ){
result=row.text();
}
for (Element row : doc.select("div[class=today_nowcard-section today_nowcard-condition]") ){
result=result+(row.text());
}
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
}
Here is the Android Manifest file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.inferno.sunshine">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-permission android:name="android.permission.INTERNET"/>
</manifest>
Use this
String GetInfo = runner.execute();
Instead of this
String GetInfo = runner.doInBackground();
try this
public class MainActivity extends AppCompatActivity {
TextView weatherInfo;
String GetInfo = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
weatherInfo = (TextView) findViewById(R.id.weather_info);
Weathers runner = new Weathers();
runner.execute();
}
}
class Weathers extends AsyncTask<String,String,String>{
String result = "";
#Override
protected String doInBackground(String... strings) {
String x="19.11";
String y="72.88";
try {
Document doc = Jsoup.connect("https://weather.com/en-IN/weather/today/l/"+x+","+y).get();
for (Element row : doc.select("header[class=loc-container]") ){
result=row.text();
}
for (Element row : doc.select("div[class=today_nowcard-section today_nowcard-condition]") ){
result=result+(row.text());
}
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
#Override
protected void onPostExecute(Void aVoid) {
weatherInfo.append(result);
}
}

Class Parcelable with ArrayList of Objects

I'm trying to use Parcelable on a class that contains ArrayList of Objects.
I'm getting an error when trying to write the list.
the class -
public class Library implements Parcelable {
ArrayList<Station> stations;
private String[] stationNames;
private String[] stationsDescription;
private int[] images;
private String[] streamLinks;
public Library(String[] stationNames, String[] stationsDescription, int[] images, String[] streamLinks) {
//instantiationCounter++;
this.stationNames = stationNames;
this.stationsDescription = stationsDescription;
this.images = images;
this.streamLinks = streamLinks;
this.stations = new ArrayList<>();
for (int i = 0; i < stationNames.length; i++) {
stations.add(new Station(stationNames[i], stationsDescription[i], streamLinks[i], images[i]));
}
}
public Library() {
}
protected Library(Parcel in) {
stationNames = in.createStringArray();
stationsDescription = in.createStringArray();
images = in.createIntArray();
streamLinks = in.createStringArray();
stationNames = in.createStringArray();
stations = in.readArrayList(null);
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeStringArray(stationNames);
dest.writeStringArray(stationsDescription);
dest.writeIntArray(images);
dest.writeStringArray(streamLinks);
dest.writeList(stations);
}
Logcat -
java.lang.RuntimeException: Parcel: unable to marshal value com.tsuryohananov.israeliradio.Station#8b5e126
at android.os.Parcel.writeValue(Parcel.java:1711)
at android.os.Parcel.writeList(Parcel.java:865)
at com.tsuryohananov.israeliradio.Library.writeToParcel(Library.java:65)
at android.os.Parcel.writeParcelable(Parcel.java:1730)
at android.os.Parcel.writeValue(Parcel.java:1636)
at android.os.Parcel.writeArrayMapInternal(Parcel.java:777)
at android.os.BaseBundle.writeToParcelInner(BaseBundle.java:1506)
at android.os.Bundle.writeToParcel(Bundle.java:1181)
at android.os.Parcel.writeBundle(Parcel.java:817)
at android.content.Intent.writeToParcel(Intent.java:9480)
at android.app.IActivityManager$Stub$Proxy.startService(IActivityManager.java:4877)
at android.app.ContextImpl.startServiceCommon(ContextImpl.java:1491)
at android.app.ContextImpl.startService(ContextImpl.java:1461)
at android.content.ContextWrapper.startService(ContextWrapper.java:644)
at com.tsuryohananov.israeliradio.Tab1Fragment$1.onItemClick(Tab1Fragment.java:95)
at android.widget.AdapterView.performItemClick(AdapterView.java:318)
at android.widget.AbsListView.performItemClick(AbsListView.java:1165)
at android.widget.AbsListView$PerformClick.run(AbsListView.java:3134)
at android.widget.AbsListView$3.run(AbsListView.java:4049)
at android.os.Handler.handleCallback(Handler.java:789)
at android.os.Handler.dispatchMessage(Handler.java:98)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6541)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
Update:
Station is now implementing Parcelable as well, as Naveen Dew suggested.
Station class-
public class Station implements Parcelable {
String name;
String description;
String streamLink;
int img;
public Station(String name, String description, String streamLink, int img) {
this.name = name;
this.description = description;
this.streamLink = streamLink;
this.img = img;
}
protected Station(Parcel in) {
name = in.readString();
description = in.readString();
streamLink = in.readString();
img = in.readInt();
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(name);
dest.writeString(description);
dest.writeString(streamLink);
dest.writeInt(img);
}
#Override
public int describeContents() {
return 0;
}
public static final Creator<Station> CREATOR = new Creator<Station>() {
#Override
public Station createFromParcel(Parcel in) {
return new Station(in);
}
#Override
public Station[] newArray(int size) {
return new Station[size];
}
};
String getStationName() {
return name;
}
String getDescription() {
return description;
}
String getStreamLink() {
return streamLink;
}
int getStationImg() {
return img;
}
void details() {
System.out.println(name);
System.out.println(description);
System.out.println(streamLink);
System.out.println(img);
System.out.println("--------------");
}
}
I'm facing a problem when passing the Library parcel to Service iv'e made for sound.
this is how i'm sending extra on intent to the the service -
Intent serviceIntent = new Intent(getActivity(), BackgroundSoundService.class);
serviceIntent.putExtra("Library", (Parcelable) mainLibrary);
serviceIntent.putExtra("position", position);
getContext().startService(serviceIntent);
here i'm trying to get the Library in the BackGroundSoundService -
public int onStartCommand(Intent intent, int flags, int startId) {
library = (Library) intent.getParcelableExtra("Library");
position = intent.getIntExtra("position", 0);
}
Can not start the service!
Logcat -
java.lang.RuntimeException: Unable to start service com.tsuryohananov.israeliradio.BackgroundSoundService#823fbd with Intent { cmp=com.tsuryohananov.israeliradio/.BackgroundSoundService (has extras) }: java.lang.RuntimeException: Parcel android.os.Parcel#5f24b14: Unmarshalling unknown type code 7274617 at offset 10964
at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:3556)
at android.app.ActivityThread.-wrap20(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1698)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6541)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
Caused by: java.lang.RuntimeException: Parcel android.os.Parcel#5f24b14: Unmarshalling unknown type code 7274617 at offset 10964
at android.os.Parcel.readValue(Parcel.java:2754)
at android.os.Parcel.readListInternal(Parcel.java:3103)
at android.os.Parcel.readArrayList(Parcel.java:2305)
at com.tsuryohananov.israeliradio.Library.(Library.java:64)
at com.tsuryohananov.israeliradio.Library$1.createFromParcel(Library.java:103)
at com.tsuryohananov.israeliradio.Library$1.createFromParcel(Library.java:100)
at android.os.Parcel.readParcelable(Parcel.java:2781)
at android.os.Parcel.readValue(Parcel.java:2675)
at android.os.Parcel.readArrayMapInternal(Parcel.java:3042)
at android.os.BaseBundle.unparcel(BaseBundle.java:257)
at android.os.Bundle.getParcelable(Bundle.java:888)
at com.tsuryohananov.israeliradio.BackgroundSoundService.onStartCommand(BackgroundSoundService.java:62)
at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:3539)
Update -
manifest -
<?xml version="1.0" encoding="utf-8"?>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity
android:name=".MainActivity"
android:configChanges="orientation|screenSize"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<!--
<activity
android:name=".NotificationView"
android:configChanges="orientation|screenSize"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar">
</activity>
-->
<service
android:name=".BackgroundSoundService"
android:label="My Service">
</service>
<activity android:name=".PlayActivity"></activity>
</application>
your inner classes should also be Parcelable
check if Station is implementing Parcelable
UPDATE
Creator is missing from Library class
add this to your library class
public static final Creator<Library> CREATOR = new Creator<Library>() {
#Override
public Library createFromParcel(Parcel in) {
return new Library(in);
}
#Override
public Library[] newArray(int size) {
return new Library[size];
}
};
also please post your Manifest file

Class or interface expected - Provider name

I'm trying to declare my content provider class in the manifest but it shows me an error when I type the name of the fully qualified name of the provider class:
The error is Class or Interface expected, what does that mean?
the error was at this line: android:name="com.sns.awesomecharactercreator.CharacterProvider" There is a red line underit and when I hover over it says class or interface expected
Here is the code:
<?xml version="1.0" encoding="utf-8"?>
<!--suppress ALL -->
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.sns.awesomecharactercreator" >
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".Welcome"
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=".EditingCharacter"
android:label="#string/title_activity_general_characteristics"
android:parentActivityName=".Notes" >
</activity>
<provider
android:authorities="com.sns.awesomecharactercreator.characterprovider"
android:name="com.sns.awesomecharactercreator.CharacterProvider"
android:exported="false" />
</application>
CharacterProvider class:
package com.sns.awesomecharactercreator;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import DATALAYER.DBHelper;
public class CharacterProvider extends android.content.ContentProvider {
private final static String AUTHORITY = "com.sns.awesomecharactercreator.characterprovider";
private final static String BASE_PATH = "characterattributes";
public final static Uri CONTENT_URI =
Uri.parse("content://" + AUTHORITY + "/" + BASE_PATH);
private static final int CHARACTERS = 1;
private static final int CHARACTERS_ID = 2;
private static final UriMatcher uriMatcher =
new UriMatcher(UriMatcher.NO_MATCH);
static {
uriMatcher.addURI(AUTHORITY, BASE_PATH, CHARACTERS);
uriMatcher.addURI(AUTHORITY, BASE_PATH + "/#", CHARACTERS_ID);
}
private static final String[] allColumns = {
DBHelper.CHARACTERATTRIBUTES_ID,
DBHelper.CHARACTERATTRIBUTES_NAME,
DBHelper.CHARACTERATTRIBUTES_MEANING,
DBHelper.CHARACTERATTRIBUTES_NICKNAME,
DBHelper.CHARACTERATTRIBUTES_RELIGION,
DBHelper.CHARACTERATTRIBUTES_BIRTHDATE,
DBHelper.CHARACTERATTRIBUTES_BIRTHPLACE,
DBHelper.CHARACTERATTRIBUTES_SIGN,
DBHelper.CHARACTERATTRIBUTES_TALENTS,
DBHelper.CHARACTERATTRIBUTES_MAINSEC,
DBHelper.CHARACTERATTRIBUTES_WEAPONS,
DBHelper.CHARACTERATTRIBUTES_CLASSS,
DBHelper.CHARACTERATTRIBUTES_STRENGTHS,
DBHelper.CHARACTERATTRIBUTES_WEAKNESSES,
DBHelper.CHARACTERATTRIBUTES_ROLE,
DBHelper.CHARACTERATTRIBUTES_VOICE,
DBHelper.CHARACTERATTRIBUTES_SECRETS,
DBHelper.CHARACTERATTRIBUTES_PROFESSION,
DBHelper.CHARACTERATTRIBUTES_QUOTE,
DBHelper.CHARACTERATTRIBUTES_AGE,
DBHelper.CHARACTERATTRIBUTES_BODYTYPE,
DBHelper.CHARACTERATTRIBUTES_HEIGHT,
DBHelper.CHARACTERATTRIBUTES_WEIGHT,
DBHelper.CHARACTERATTRIBUTES_FACESHAPE,
DBHelper.CHARACTERATTRIBUTES_EYECOLOR,
DBHelper.CHARACTERATTRIBUTES_HAIRCOLOR,
DBHelper.CHARACTERATTRIBUTES_HAIRSTYLE,
DBHelper.CHARACTERATTRIBUTES_SPECIALFEATURES,
DBHelper.CHARACTERATTRIBUTES_HEALTH,
DBHelper.CHARACTERATTRIBUTES_DISABILITIES,
DBHelper.CHARACTERATTRIBUTES_SKINTONE,
DBHelper.CHARACTERATTRIBUTES_ACCESORIES,
DBHelper.CHARACTERATTRIBUTES_CLOTHES,
DBHelper.CHARACTERATTRIBUTES_ALOOKALIKE,
DBHelper.CHARACTERATTRIBUTES_ETHNICITY,
DBHelper.CHARACTERATTRIBUTES_IQLEVEL,
DBHelper.CHARACTERATTRIBUTES_EDUCATION,
DBHelper.CHARACTERATTRIBUTES_DOMINANTMOOD,
DBHelper.CHARACTERATTRIBUTES_MORALCODES,
DBHelper.CHARACTERATTRIBUTES_DESIRES,
DBHelper.CHARACTERATTRIBUTES_DISLIKES,
DBHelper.CHARACTERATTRIBUTES_ATTITUDES,
DBHelper.CHARACTERATTRIBUTES_EMOTIONHANDLING,
DBHelper.CHARACTERATTRIBUTES_QUALITIES,
DBHelper.CHARACTERATTRIBUTES_FLAWS,
DBHelper.CHARACTERATTRIBUTES_GOALS,
DBHelper.CHARACTERATTRIBUTES_POPULARITY,
DBHelper.CHARACTERATTRIBUTES_REPUTATION,
DBHelper.CHARACTERATTRIBUTES_CHARISMA,
DBHelper.CHARACTERATTRIBUTES_RELATIVES,
DBHelper.CHARACTERATTRIBUTES_COMPANIONS,
DBHelper.CHARACTERATTRIBUTES_LOVELIFE,
DBHelper.CHARACTERATTRIBUTES_NOTES};
private SQLiteDatabase db;
#Override
public boolean onCreate() {
DBHelper helper = new DBHelper(getContext());
db = helper.getWritableDatabase();
return true;
}
#Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
return db.query(DBHelper.TABLE_CHARACTERATTRIBUTES, allColumns, selection, null, null, null, null);
}
#Override
public String getType(Uri uri) {
return null;
}
#Override
public Uri insert(Uri uri, ContentValues values) {
long id = db.insert(DBHelper.TABLE_CHARACTERATTRIBUTES, null, values);
return Uri.parse(BASE_PATH + "/#" + id);
}
#Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
return db.delete(DBHelper.TABLE_CHARACTERATTRIBUTES, selection, selectionArgs);
}
#Override`enter code here`
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
return db.update(DBHelper.TABLE_CHARACTERATTRIBUTES,values,selection,selectionArgs);
}
}
Could someone be a dear and help me here? I'm stuck for like forever and I'm nearly ripping my hair off.

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