Internet Based Store Data in Firebase and Sqlitedatabse


Internet Based Store Data in Firebase and Sqlitedatabse


Output Screen







AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.internetchecking">

<uses-permission-sdk-23 android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission-sdk-23 android:name="android.permission.INTERNET" />

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:name=".SingleTask"
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>
<receiver
android:name=".InternetCheck"
android:exported="false">
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>
</application>

</manifest>


main_activity.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">


<Button
android:id="@+id/button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:onClick="checkInternet"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.162" />

<EditText
android:id="@+id/tname"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:ems="10"
android:hint="Enter Name"
android:inputType="textPersonName"
android:padding="20dp"
app:layout_constraintBottom_toTopOf="@+id/button"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.156" />

<ListView
android:id="@+id/mylist"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintTop_toBottomOf="@+id/button"
app:layout_constraintVertical_bias="0.094"
tools:layout_editor_absoluteX="0dp" />

</androidx.constraintlayout.widget.ConstraintLayout>


MainActivity.java
package com.example.internetchecking;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class MainActivity extends AppCompatActivity {
private InternetCheck internetCheck;
private Database db;
private EditText tname;
private DatabaseReference databaseReference;
private ListView listView;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FirebaseDatabase database = FirebaseDatabase.getInstance();
databaseReference = database.getReference("student");

db = new Database(this);
internetCheck = new InternetCheck();

registerNetworkBroadcastForNougat();

tname = findViewById(R.id.tname);
listView = findViewById(R.id.mylist);

getDataFromeServer();

}

private void registerNetworkBroadcastForNougat() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
registerReceiver(internetCheck, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
registerReceiver(internetCheck, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
}
}

private String name;

public void checkInternet(View view) {
name = tname.getText().toString();
Student student = new Student();
student.setName(name);

if (SingleTask.status) {
student.setStatus(1);
Toast.makeText(this, "Available", Toast.LENGTH_SHORT).show();
sendToServer(student);
} else {
student.setStatus(0);
Toast.makeText(this, "Not Available", Toast.LENGTH_SHORT).show();
sendToLocalDatabase(student);
}
}

private void sendToServer(Student student) {
Log.e("error", "upload to server " + student.getName());
databaseReference.push().setValue(student).
        addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (task.isSuccessful()) {
Toast.makeText(MainActivity.this, "Store Successfully", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, "Store Failed", Toast.LENGTH_SHORT).show();
}
}
});
}

private void sendToLocalDatabase(Student student) {
Log.e("error", "upload to local database " + student.getName());
long i = db.insert(student);
if (i > 0) {
Toast.makeText(MainActivity.this, "Store Successfully", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, "Store Failed", Toast.LENGTH_SHORT).show();
}
}

private List<Student> list;

private void getDataFromeServer() {

databaseReference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
list = new ArrayList<>();
Iterator<DataSnapshot> ds = dataSnapshot.getChildren().iterator();
while (ds.hasNext()) {
DataSnapshot dss = ds.next();
list.add(dss.getValue(Student.class));
}
listView.setAdapter(new ArrayAdapter<Student>
                (MainActivity.this, android.R.layout.simple_list_item_1, list));
}


@Override
public void onCancelled(@NonNull DatabaseError databaseError) {

}
});
}


}

InternetCheck.java
package com.example.internetchecking;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;
import android.widget.Toast;

import androidx.annotation.NonNull;

import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;

import java.util.List;

public class InternetCheck extends BroadcastReceiver {
private Database db;
private DatabaseReference databaseReference;

@Override
public void onReceive(Context context, Intent intent) {
db = new Database(context);
FirebaseDatabase database = FirebaseDatabase.getInstance();
databaseReference = database.getReference("student");
isNetworkAvailable(context);
}

public void isNetworkAvailable(Context context) {
ConnectivityManager connectivityManager = (ConnectivityManager)
        context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
if (activeNetworkInfo != null && activeNetworkInfo.isConnected()) {
SingleTask.status = true;
Toast.makeText(context, "Internet is available", Toast.LENGTH_SHORT).show();
//upload to server
List<Student> list = db.getOfflineStudent();
if (list.size() > 0) {
for (Student student : list) {
sendToServer(student);
}
}
} else {
SingleTask.status = false;
Toast.makeText(context, "Internet is not available", Toast.LENGTH_LONG).show();
//upload to local database
}
}

private void sendToServer(final Student student) {
Log.e("error", "upload to server " + student.getName());
student.setStatus(1);
databaseReference.push().setValue(student).
        addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (task.isSuccessful()) {
int i = db.updateStatus(student);
Log.e("error", "success");
}
}
});


}
}


SingleTask.java
package com.example.internetchecking;

import android.app.Application;

public class SingleTask extends Application {
public static boolean status = false;
@Override
public void onCreate() {
super.onCreate();
}

}

Student.java
package com.example.internetchecking;

import androidx.annotation.NonNull;

public class Student {
private int status;
private String name;

public int getStatus() {
return status;
}

public void setStatus(int status) {
this.status = status;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

@NonNull
@Override
public String toString() {
return name + "\t\t\t" + status;
}
}

Database.java
package com.example.internetchecking;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import androidx.annotation.Nullable;

import java.util.ArrayList;
import java.util.List;

public class Database extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "college";
private static final String TABLE_NAME = "student";
private static final String NAME = "name";
private static final String STATUS = "status";

private static final String CREATE_QUERY =
     "create table " + TABLE_NAME + " (" + NAME + " varchar(30)," + STATUS + " int);";


public Database(@Nullable Context context) {
super(context, DATABASE_NAME, null, 1);
}

@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
sqLiteDatabase.execSQL(CREATE_QUERY);
}

@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
sqLiteDatabase.execSQL("drop table if exists " + TABLE_NAME + "");
onCreate(sqLiteDatabase);
}

public long insert(Student student) {
ContentValues cv = new ContentValues();
cv.put(NAME, student.getName());
cv.put(STATUS, student.getStatus());
return getWritableDatabase().insert(TABLE_NAME, null, cv);
}

public List<Student> getOfflineStudent() {
List<Student> list = new ArrayList<>();
        Cursor cursor = getReadableDatabase().
        query(TABLE_NAME, null, "" + STATUS + "=?", 
        new String[]{String.valueOf(0)}, null, null, null, null);

while (cursor.moveToNext()) {
Student s = new Student();
s.setName(cursor.getString(0));
s.setStatus(cursor.getInt(1));
list.add(s);
}
return list;
}

public int updateStatus(Student student) {
ContentValues cv = new ContentValues();
cv.put(NAME, student.getName());
cv.put(STATUS, student.getStatus());
return getWritableDatabase().
        update(TABLE_NAME, cv, "" + NAME + "=?", new String[]{student.getName()});
}

}


1 comment:

Suriyal said...

Thank you for this excellent code sir, very helpful while thinking of SQLite-Firebase sync