Passing string from one MainActivity to another DB Class Java - java

How to pass a string from a TextView populated from spiner onItemSelected event to make query in DBController class. I can't implement intent:
Main14Activity
Nidd.setText(imc_met.substring(imc_met.lastIndexOf("Id") + 3));
String ado = Nidd.getText().toString();
DBController
String selectQuery = "SELECT * FROM proinfo WHERE Name= " + .... ;
Intent is not working, because I don't know how to get this working. The function getintent(). Returns red in DB class.
Main14Activity Code:
public class Main14Activity extends ListActivity {
TextView lbl;
DBController controller = new DBController(this);
ListView lv;
final Context context = this;
ListAdapter adapter;
ArrayList<HashMap<String, String>> myList;
ArrayList<String> myList1;
Spinner spinner12;
TextView Nidd;
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main142);
lbl = (TextView) findViewById(R.id.txtresulttext);
Nidd = (TextView) findViewById(R.id.Nidd);
lv = getListView();
spinner12 = (Spinner) findViewById(R.id.spinner12);
myList1 = controller.getAllProducts1();
Spinner My_spinner = (Spinner) findViewById(R.id.spinner12);
ArrayAdapter adapter1 = new ArrayAdapter(this, R.layout.spinner_row,
myList1);
My_spinner.setAdapter(adapter1);
controller = new DBController(getApplicationContext());
SQLiteDatabase db = controller.getWritableDatabase();
String tableName = "proinfo";
db.execSQL("delete from " + tableName);
try {
try {
String filename = "/Download/jobtex.csv";
String path = Environment.getExternalStorageDirectory() + filename;
FileReader file = new FileReader(path);
BufferedReader buffer = new BufferedReader(file);
ContentValues contentValues = new ContentValues();
String line = "";
db.beginTransaction();
while ((line = buffer.readLine()) != null) {
String[] str = line.split(",", 3); // defining 3 columns with null or blank field //values acceptance
//Job, Nid
// String company = str[0].toString();
String company = str[0].toString();
String Name = str[1].toString();
// String Price = str[2].toString();
contentValues.put("Company", company);
contentValues.put("Name", Name);
// contentValues.put("Price", Price);
db.insert(tableName, null, contentValues);
lbl.setText("Successfully Updated Database.");
}
db.setTransactionSuccessful();
db.endTransaction();
} catch (IOException e) {
if (db.inTransaction())
db.endTransaction();
Dialog d = new Dialog(this);
d.setTitle(e.getMessage().toString() + "first");
d.show();
// db.endTransaction();
}
myList = controller.getAllProducts();
if (myList.size() != 0) {
ListView lv = getListView();
ListAdapter adapter = new SimpleAdapter(Main14Activity.this, myList,
R.layout.v, new String[]{"Company", "Name"}, new int[]{
R.id.txtproductcompany, R.id.txtproductname});
setListAdapter(adapter);
lbl.setText("Data Imported");
myList1 = controller.getAllProducts1();
My_spinner = (Spinner) findViewById(R.id.spinner12);
adapter1 = new ArrayAdapter(this, R.layout.spinner_row,
myList1);
My_spinner.setAdapter(adapter1);
My_spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
String imc_met = spinner12.getSelectedItem().toString();
Nidd.setText(imc_met.substring(imc_met.lastIndexOf("Id") + 3));
String ado = Nidd.getText().toString();
Fragment fragment = new Fragment();
???????????????
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
} finally {
}
}
}
DBController: DB Class
public class DBController extends SQLiteOpenHelper {
private static final String LOGCAT = null;
public DBController(Context applicationcontext) {
super(applicationcontext, "PrdouctDB.db", null, 1); // creating DATABASE
Log.d(LOGCAT, "Created");
}
#Override
public void onCreate(SQLiteDatabase database) {
String query;
query = "CREATE TABLE IF NOT EXISTS proinfo ( Id INTEGER PRIMARY KEY, Company TEXT,Name TEXT)";
database.execSQL(query);
}
#Override
public void onUpgrade(SQLiteDatabase database, int version_old,
int current_version) {
String query;
query = "DROP TABLE IF EXISTS proinfo" ;
database.execSQL(query);
onCreate(database);
}
public ArrayList<HashMap<String, String>> getAllProducts() {
ArrayList<HashMap<String, String>> proList;
proList = new ArrayList<HashMap<String, String>>();
String selectQuery = "SELECT * FROM proinfo WHERE Name=" + ??????????????????? ;
SQLiteDatabase database = this.getWritableDatabase();
Cursor cursor = database.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
//Id, Company,Name,Price
HashMap<String, String> map = new HashMap<String, String>();
map.put("Id", cursor.getString(0));
map.put("Company", cursor.getString(1));
map.put("Name", cursor.getString(2));
// map.put("Price", cursor.getString(3));
proList.add(map);
} while (cursor.moveToNext());
}
return proList;
}
public ArrayList<String> getAllProducts1() {
ArrayList<String> proList1;
proList1 = new ArrayList<String>();
String selectQuery = "SELECT * FROM proinfo ";
SQLiteDatabase database = this.getWritableDatabase();
Cursor cursor = database.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
String add = "Job Id";
String as = "Site:";
String space = " ";
proList1.add( as + space + cursor.getString(1) + space + add + space + cursor.getString(2));
} while (cursor.moveToNext());
}
cursor.close();
database.close();
return proList1;
}
}

Related

How to automatically refresh data in a recycleview android

I have a recycle view which gets data from an sql table,its basically like a chat system app.
but of course i need to refresh data every time it changes,however i tried using .notifyDataSetChanged().
but it couldn't appear to be working for me,can anyone help me with this task According to my code
here is my code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
getSupportActionBar().hide();
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
emojiButton = findViewById(R.id.emoji_button);
submitButton = findViewById(R.id.submit_button);
emojiconEditText = findViewById(R.id.emojicon_edit_text);
emojIconActions = new EmojIconActions(getApplicationContext(),activity_chat,emojiButton,emojiconEditText);
SyncData syncData = new SyncData();
syncData.SyncoData("");
syncData.execute();
//emojIconActions.ShowEmojicon();
submitButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try{
String editTextData = emojiconEditText.getText().toString();
SyncData orderdata = new SyncData();
orderdata.SyncData(editTextData);
Date c = Calendar.getInstance().getTime();
SimpleDateFormat df = new SimpleDateFormat("MM/dd/yyyy");
String formattedDate = df.format(c);
orderdata.SyncoData("Insert into CustomerSupportChat values('" + formattedDate + "','" + editTextData + "','Customer','3','" + getIntent().getStringExtra("nameid") + "','1','1') ");
orderdata.execute();
emojiconEditText.setText("");
emojiconEditText.requestFocus();
}
catch(Exception e) {
Log.e("ActivityName", "Exception caused by editText " + e.toString());
}
}
});
connectionClass = new ConnectionClass();
itemArrayList = new ArrayList<ClassListChat>();
listOfMessage = findViewById(R.id.list_of_message);
MyAppAdapter appAdapter = new MyAppAdapter(itemArrayList,ChatActivity.this);
listOfMessage.setAdapter(appAdapter);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(ChatActivity.this);
linearLayoutManager.setReverseLayout(true);
listOfMessage.setLayoutManager(linearLayoutManager);
}
private class SyncData extends AsyncTask<String, String, String> {
String msg;
ProgressDialog progress;
String editTextData;
Date c = Calendar.getInstance().getTime();
SimpleDateFormat df = new SimpleDateFormat("MM/dd/yyyy");
String formattedDate = df.format(c);
public void SyncData(String editTextData) {
this.editTextData = editTextData;
}
String inquery = "Insert into CustomerSupportChat values('" + formattedDate + "','" + editTextData + "','Customer','3','" + getIntent().getStringExtra("nameid") + "','1','1') ";
public void SyncoData(String inquery) {
this.inquery = inquery;
}
#Override
protected void onPreExecute() //Starts the progress dailog
{
progress = ProgressDialog.show(ChatActivity.this, "Loading...",
"Please Wait...", true);
}
#Override
protected String doInBackground(String... strings) // Connect to the database, write query and add items to array list
{
runOnUiThread(new Runnable() {
public void run() {
try {
Connection conn = connectionClass.CONN(); //Connection Object
if (conn == null) {
success = false;
msg = "Sorry something went wrong,Please check your internet connection";
} else {
// Change below query according to your own database.
Date c = Calendar.getInstance().getTime();
SimpleDateFormat df = new SimpleDateFormat("MM/dd/yyyy");
String formattedDate = df.format(c);
System.out.println("it isssssssssssssssssssssssssssssssssssssssssaaaaaaaaaaaaaaaaaaaa" + formattedDate);
String query = inquery +
"Select MessageID,MessageDate,MessageText,SenderType,MessageRecieved,MessageReaded,CustomerData.CustomerName,StoresData.StoreEnglishName,StoresData.StoreArabicName FROM " +
"CustomerSupportChat INNER JOIN CustomerData ON " +
"CustomerSupportChat.CustomerID = CustomerData.CustomerID INNER JOIN StoresData ON " +
"CustomerSupportChat.StoreID = StoresData.StoreID ORDER BY MessageID DESC";
// String query2 =
// "Select MessageID,MessageDate,MessageText,SenderType,MessageRecieved,MessageReaded,Users_Login_Data.Username,StoresData.StoreEnglishName,StoresData.StoreArabicName FROM " +
// "CustomerSupportChat INNER JOIN Users_Login_Data ON " +
// "CustomerSupportChat.CustomerID = Users_Login_Data.CustomerID INNER JOIN StoresData ON " +
// "CustomerSupportChat.StoreID = StoresData.StoreID Where SenderType = 'Store' ORDER BY MessageID DESC";
//Statement stmt2 = conn.createStatement();
// ResultSet rs2 = stmt2.executeQuery(query2);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(query);
itemArrayList.clear();
if (rs != null) // if resultset not null, I add items to itemArraylist using class created
{
while (rs.next()) {
try {
itemArrayList.add(new ClassListChat(rs.getString("MessageText"), rs.getString("SenderType"), rs.getString("MessageText")));
} catch (Exception ex) {
ex.printStackTrace();
}
}
msg = "Found";
success = true;
} else {
msg = "No Data found!";
success = false;
}
// if ( rs2 != null){
// while (rs2.next()){
// itemArrayList.add(new ClassListChat("","Store",rs2.getString("MessageText")));
// }
// }
}
} catch (Exception e) {
e.printStackTrace();
Writer writer = new StringWriter();
e.printStackTrace(new PrintWriter(writer));
msg = writer.toString();
Log.d("Error", writer.toString());
success = false;
}
}
});
return msg;
}
#Override
protected void onPostExecute(String msg) // disimissing progress dialoge, showing error and setting up my listview
{
progress.dismiss();
if (msg != null) {
Toast.makeText(ChatActivity.this, msg + "", Toast.LENGTH_LONG).show();
}
if (!success) {
Toast.makeText(ChatActivity.this,"ERROR " + msg,Toast.LENGTH_LONG).show();
} else {
try {
MyAppAdapter appAdapter = new MyAppAdapter(itemArrayList,ChatActivity.this);
listOfMessage.setAdapter(appAdapter);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(ChatActivity.this);
linearLayoutManager.setReverseLayout(true);
listOfMessage.setLayoutManager(linearLayoutManager);
} catch (Exception ex) {
}
}
}
}
public class MyAppAdapter extends RecyclerView.Adapter<MyAppAdapter.ViewHolder>//has a class viewholder which holds
{
private ArrayList<ClassListChat> mOriginalValues; // Original Values
private ArrayList<ClassListChat> mDisplayedValues;
public class ViewHolder extends RecyclerView.ViewHolder {
TextView messageText;
TextView messageStore;
TextView messageUser;
TextView messageTime;
public ViewHolder(#NonNull View itemView) {
super(itemView);
messageText = itemView.findViewById(R.id.message_text);
messageUser = itemView.findViewById(R.id.message_user);
messageTime = itemView.findViewById(R.id.message_time);
messageStore = itemView.findViewById(R.id.message_text_store);
}
}
public List <ClassListChat> parkingList;
public Context context;
ArrayList<ClassListChat> arraylist;
private MyAppAdapter(List<ClassListChat> apps, Context context) {
this.parkingList = apps;
this.context = context;
arraylist = new ArrayList<ClassListChat>();
arraylist.addAll(parkingList);
}
#Override
public MyAppAdapter.ViewHolder onCreateViewHolder(ViewGroup parent,int viewType) {
View rowView = LayoutInflater.from(parent.getContext()).inflate(R.layout.listcontentstorechat,parent,false);
ViewHolder viewHolder = new ViewHolder(rowView);
LayoutInflater inflater = getLayoutInflater();
rowView = inflater.inflate(R.layout.listcontentstorechat, parent, false);
// here setting up names and images
return viewHolder;
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
holder.messageUser.setText(parkingList.get(position).getMessageUser());
holder.messageTime.setText(DateFormat.format("dd-MM-yyyy (HH:mm:ss)", parkingList.get(position).getMessageTime()));
if (holder.messageUser.getText().toString().equals("Store")){
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
params.topMargin = 45;
params.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
holder.messageUser.setLayoutParams(params);
holder.messageStore.setText(parkingList.get(position).getMessageOther());
}else {
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
params.topMargin = 2;
params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
holder.messageUser.setLayoutParams(params);
holder.messageText.setText(parkingList.get(position).getMessageText());
}
if (holder.messageText.getText().toString().equals("")){
holder.messageText.setVisibility(View.GONE);
}
if (holder.messageStore.getText().toString().equals("")){
holder.messageStore.setVisibility(View.GONE);
}
holder.setIsRecyclable(false);
myAppAdapter.notifyDataSetChanged();
System.out.println("COUNTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT:"+myAppAdapter.getItemCount());
}
#Override
public int getItemCount() {
return arraylist.size();
}
}
if you noticed i already added .notifyDataSetChanged() in the last line of onBindViewHolder(),but it returns an error in the logcat saying that getItemCount() is null,i also tried putting
if(arraylist != null){
return arraylist.size();
}
but it doesn't also work.
also the print statement which says "COUNTTT" doesn't print anything.
any help?!

Edittext Suggestion on android Studio

help me how to fix this code
from AutocompleteTextview i cant see the error code from this part
final String [] myData = myDB.SelectAllData();
final AutoCompleteTextView autoCom = (AutoCompleteTextView)findViewById(R.id.TVresult);
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.select_dialog_singlechoice,myData);
autoCom.setAdapter(adapter);
and This Part
public String[] SelectAllData() {
try {
String ArrayData[] = null;
SQLiteDatabase db;
db = this.getReadableDatabase(); // Read Data
String strSQL = "SELECT * FROM " + DB_TABLE_NAME;
Cursor cursor = db.rawQuery(strSQL, null);
if(cursor != null)
{
if (cursor.moveToFirst()) {
ArrayData = new String[cursor.getCount()];
/***
* [x] = Name
*/
int i= 0;
do {
ArrayData[i] = cursor.getString(0);
i++;
} while (cursor.moveToNext());
}
}
cursor.close();
return ArrayData;
} catch (Exception e) {
return null;
}
}
This is my code of MainActivity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
resulttext = (TextView) findViewById(R.id.TVresult);
rescebu = (TextView) findViewById(R.id.english);
trans = (Button) findViewById(R.id.translate);
respam = (TextView) findViewById(R.id.tagalog);
resilo = (TextView) findViewById(R.id.vis);
resbik = (TextView) findViewById(R.id.ilonngo);
myDB = new DatabaHelper(this);
tts = new TextToSpeech(this, this);
final String [] myData = myDB.SelectAllData();
final AutoCompleteTextView autoCom = (AutoCompleteTextView)findViewById(R.id.TVresult);
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.select_dialog_singlechoice,myData);
autoCom.setAdapter(adapter);
autoCom.setThreshold(1);
autoCom.setTextColor(Color.RED);
This is The Dabasehelper and SelectAllData Method
public class DatabaHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "translator4.sqlite";
private static final String DB_TABLE_NAME = "wews";
public DatabaHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
}
public Cursor getAllData(String English, String Tagalog, String Visaya, String Ilonggo) {
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.rawQuery("select * from wews where English like '" + English + "' or Tagalog like '" + Tagalog + "' or Visayan like '" + Visaya + "' or Ilonggo like '" + Ilonggo + "';", null);
return res;
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
}
public String[] SelectAllData() {
try {
String ArrayData[] = null;
SQLiteDatabase db;
db = this.getReadableDatabase(); // Read Data
String strSQL = "SELECT * FROM " + DB_TABLE_NAME;
Cursor cursor = db.rawQuery(strSQL, null);
if(cursor != null)
{
if (cursor.moveToFirst()) {
ArrayData = new String[cursor.getCount()];
/***
* [x] = Name
*/
int i= 0;
do {
ArrayData[i] = cursor.getString(0);
i++;
} while (cursor.moveToNext());
}
}
cursor.close();
return ArrayData;
} catch (Exception e) {
return null;
}
}
This is The logs LogCat
Process: application.example.com.myapplication, PID: 20663
Theme: themes:{default=overlay:system, iconPack:system, fontPkg:system, com.android.systemui=overlay:system, com.android.systemui.navbar=overlay:system}
java.lang.RuntimeException: Unable to start activity ComponentInfo{application.example.com.myapplication/application.example.com.myapplication.MainActivity}: java.lang.NullPointerException: storage == null
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2462)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2522)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1363)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5475)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
at de.robv.android.xposed.XposedBridge.main(XposedBridge.java:102)
Caused by: java.lang.NullPointerException: storage == null
at java.util.Arrays$ArrayList.<init>(Arrays.java:38)
at java.util.Arrays.asList(Arrays.java:155)
at android.widget.ArrayAdapter.<init>(ArrayAdapter.java:137)
at application.example.com.myapplication.MainActivity.onCreate(MainActivity.java:56)
at android.app.Activity.performCreate(Activity.java:7125)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1108)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2415)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2522) 
at android.app.ActivityThread.-wrap11(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1363) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:148) 
at android.app.ActivityThread.main(ActivityThread.java:5475) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 
at de.robv.android.xposed.XposedBridge.main(XposedBridge.java:102)
Possible Modification in this code block as you missed to created string object ArrayData[i] = new String() in do...while loop.
public String[] SelectAllData() {
try {
String ArrayData[] = null;
SQLiteDatabase db;
db = this.getReadableDatabase(); // Read Data
String strSQL = "SELECT * FROM " + DB_TABLE_NAME;
Cursor cursor = db.rawQuery(strSQL, null);
if(cursor != null)
{
if (cursor.moveToFirst()) {
ArrayData = new String[cursor.getCount()];
/***
* [x] = Name
*/
int i= 0;
do {
ArrayData[i] = new String();
ArrayData[i] = cursor.getString(0);
i++;
} while (cursor.moveToNext());
}
}
cursor.close();
return ArrayData;
} catch (Exception e) {
return null;
}
}
I'd suggest changing :-
public String[] SelectAllData() {
try {
String ArrayData[] = null;
SQLiteDatabase db;
db = this.getReadableDatabase(); // Read Data
String strSQL = "SELECT * FROM " + DB_TABLE_NAME;
Cursor cursor = db.rawQuery(strSQL, null);
if(cursor != null)
{
if (cursor.moveToFirst()) {
ArrayData = new String[cursor.getCount()];
/***
* [x] = Name
*/
int i= 0;
do {
ArrayData[i] = cursor.getString(0);
i++;
} while (cursor.moveToNext());
}
}
cursor.close();
return ArrayData;
} catch (Exception e) {
return null;
}
}
to :-
public String[] SelectAllData() {
try {
String ArrayData[];
SQLiteDatabase db;
db = this.getReadableDatabase(); // Read Data
String strSQL = "SELECT * FROM " + DB_TABLE_NAME;
Cursor cursor = db.rawQuery(strSQL, null);
ArrayData = new String[cursor.getCount()];
int i = 0;
while (cursor.moveToNext()) {
ArrayData[i++] = cursor.getString(0);
//ArrayData[cursor.getPosition()] = cursor.getString(0); //Could be an alternative
}
cursor.close();
return ArrayData;
} catch (Exception e) {
return new String[0];
}
}
In short, the check for a null cursor is useless it DOES NOT signify no data, rather an empty cursor with a count of 0 is returned when there is no data.
Thus when there is no data cursor.moveToFirst will be false and none of the code within the if will be executed. As such ArrayData will be null (the likely reason for the null pointer exception).
The modified code will return an empty array (0 elements) if there is no data or if there is another exception captured in the try block.
You could also do away with using a counter/index, by using cursor.getPosition(), which is effectively the same (as per commented out line).

how do i pass user-defined array parameter to asynctask in android

However, when i just check the user-defined array parameter, customerList in the outer class there are values inside but the uploadAsyncTask innerclass keeps failing on the emulator (displaying unfortunately the app has failed).
private ArrayList<CustomerData> customerList = new ArrayList<CustomerData>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
db = new DBAdapter(this);
presidents = getResources().getStringArray(R.array.presidents_array);
client = new AsyncHttpClient();
Button btn_Save, btn_Backup;
btn_Save = (Button) findViewById(R.id.btnSave);
btn_Backup = (Button) findViewById(R.id.btnBackup);
txt_AcctNum = (TextView) findViewById(R.id.txtAcctNum);
txt_AcctName = (TextView) findViewById(R.id.txtAcctName);
s1 = (Spinner) findViewById(R.id.spinner);
txt_Amt = (TextView) findViewById(R.id.txtAmt);
/*
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, presidents);
*/
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_single_choice, presidents);
s1.setAdapter(adapter);
s1.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0,
View arg1, int arg2, long arg3) {
int index = arg0.getSelectedItemPosition();
//Toast.makeText(getBaseContext(),
// "You have selected item : " + presidents[index],
// Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
-------other codes here----
btn_Backup.setOnClickListener(new Button.OnClickListener() {
#SuppressWarnings(value = "unchecked")
public void onClick(View view) {
ArrayList<CustomerData> custList = new ArrayList<CustomerData>();
// db = new DBAdapter(context);
db.open();
//db.backupToSD();
//---get all contacts---
Cursor c = db.getAllCustomers();
if (c.moveToFirst()) {
do {
//DisplayContact(c);
//sendData();
custList = addAndDisplayCustomer(c);
} while (c.moveToNext());
}
/* for (int i = 0; i < custList.size(); i++) {
Toast.makeText(getApplicationContext(), "---Customer Data--- " + "id: " +
custList.get(i).getId() + " Acct Name: " +
custList.get(i).getAcctName() + " Acct Num: " +
custList.get(i).getAcctNum() + " Tnx type: " +
custList.get(i).getTxnType() + " Amt: " +
custList.get(i).getAmt(), Toast.LENGTH_LONG).show(); }*/
Toast.makeText(getApplicationContext(), " Uploading data ... " + custList.get(0).getId(), Toast.LENGTH_LONG).show();
UploadASyncTask upload = new UploadASyncTask();
upload.execute(custList);
}
public ArrayList<CustomerData> addAndDisplayCustomer(Cursor c)
{
CustomerData customer = new CustomerData(c.getString(0), c.getString(1),
c.getString(2), c.getString(3), c.getString(4));
customerList.add(customer);
return customerList;
}
//int delRows = db.deleteAll();
//db.backupToSD();
//db.dropTable();
//Toast.makeText(getApplicationContext(), " Table successfully dropped ! ", Toast.LENGTH_LONG).show();
//db.close();
});
}
private class UploadASyncTask extends AsyncTask<ArrayList<CustomerData>, Void, Void> {
private Cursor c;
private String id;
private String acct_Name ;
private String acct_Num;
private String txnType;
private String amt;
//private ArrayList<CustomerData> custList;
private Context mContext1;
private ProgressDialog dialog = null;
private Context mContext = null;
#Override
protected void onPreExecute() {
dialog = new ProgressDialog(MainActivity.this);
dialog.setTitle(" Sending to the server... ");
dialog.setMessage("Please wait...");
dialog.setProgressDrawable(mContext.getWallpaper());
dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
dialog.setCancelable(false);
dialog.show();
}
#Override
#SafeVarargs
final protected Void doInBackground(ArrayList<CustomerData>... custList) {
try {
ArrayList<CustomerData> custom = custList[0];
for (int i = 0; i<custom.size(); i++) {
String id = custom.get(i).getId();
String acct_Name = custom.get(i).getAcctName();
String acct_Num = custom.get(i).getAcctNum();
String txnType = custom.get(i).getTxnType();
String amt = custom.get(i).getAmt();
/*runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "Welcome guy: " + id,
Toast.LENGTH_LONG).show();
}
});*/
HttpParams params = new BasicHttpParams();
HttpClient httpclient = new DefaultHttpClient(params);
HttpPost httpPost = new HttpPost
("http://10.0.2.2:8080/RestWebService/rest/customer");
List<NameValuePair> postParams = new ArrayList<NameValuePair>();
postParams.add(new BasicNameValuePair("id", id));
postParams.add(new BasicNameValuePair("acct_name", acct_Name));
postParams.add(new BasicNameValuePair("acct_num", acct_Num));
postParams.add(new BasicNameValuePair("txn_type", txnType));
postParams.add(new BasicNameValuePair("amt", amt));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(postParams);
entity.setContentEncoding(HTTP.UTF_8);
httpPost.setEntity(entity);
HttpResponse httpResponse = httpclient.execute(httpPost);
InputStream inputStream = httpResponse.getEntity().getContent();
String result = "";
id = "";
acct_Name = "";
acct_Num = "";
txnType = "";
amt = "";
}
}
catch (Exception e)
{
Log.e("Server Error: ",e.getMessage());
}
return null;
}
#Override
protected void onPostExecute(Void result) {
//custList.clear();
dialog.dismiss();
}
}
}
When I saw your code : there is a little problem. I don't know it's the good answer but :
private Context mContext = null;
and
dialog.setProgressDrawable(mContext.getWallpaper());
It's a nullPointerException in this line
For me You can delete the context and the cursor on your AsyncTask. Create a constructor on your AsyncTask and put the context in parameters, use it for the progressDialog
Hope it's help

My Database is not updated,if my JSON data will increase also

I am parsing JSON data to database,that data shows in my lisview.But in the first time it get data from my JSON and stores in db,its not upgrading if i add anything in my website,the json also will increase but its not reflect in db,the database part also not upgrading.Just its simply the display the first fetched data only.
Ginfydbadapter.java
public class GinfyDbAdapter {
private static final String DATABASE_NAME = "test";
private static final String DATABASE_TABLE_PROJ = "projects";
private static final int DATABASE_VERSION = 3;
public static final String CATEGORY_COLUMN_ID = "_id";
public static final String CATEGORY_COLUMN_TITLE = "title";
public static final String CATEGORY_COLUMN_CONTENT = "content";
public static final String CATEGORY_COLUMN_COUNT = "count";
private static final String TAG = "GinfyDbAdapter";
private DatabaseHelper mDbHelper;
private static SQLiteDatabase mDb;
private final Context mCtx;
public void saveCategoryRecord(String id, String title, String content, String count) {
ContentValues contentValues = new ContentValues();
contentValues.put(CATEGORY_COLUMN_ID, id);
contentValues.put(CATEGORY_COLUMN_TITLE, title);
contentValues.put(CATEGORY_COLUMN_CONTENT, content);
contentValues.put(CATEGORY_COLUMN_COUNT, count);
mDb.insert(DATABASE_NAME, null, contentValues);
}
public Cursor getTimeRecordList() {
return mDb.rawQuery("select * from " + DATABASE_NAME, null);
}
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
private static final String DATABASE_CREATE_PROJ =
"create table " + DATABASE_TABLE_PROJ + " ("
+ CATEGORY_COLUMN_ID + " integer primary key , "
+ CATEGORY_COLUMN_TITLE + " text not null, " + CATEGORY_COLUMN_CONTENT + " text not null, " + CATEGORY_COLUMN_COUNT + " integer );" ;
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
String DATABASE_CREATE_PROJ = "CREATE TABLE " + DATABASE_TABLE_PROJ + "( "
+ CATEGORY_COLUMN_ID + " integer primary key, "
+ CATEGORY_COLUMN_TITLE + " text not null, " + CATEGORY_COLUMN_CONTENT + " text not null, " + CATEGORY_COLUMN_COUNT + " integer );" ;
db.execSQL(DATABASE_CREATE_PROJ);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS"+ DATABASE_TABLE_PROJ);
onCreate(db);
}
}
public void saveCategoryRecord(Category category) {
ContentValues values = new ContentValues();
values.put(CATEGORY_COLUMN_TITLE , category.getTitle());
values.put(CATEGORY_COLUMN_CONTENT, category.getContent());
values.put(CATEGORY_COLUMN_COUNT, category.getCount());
// Inserting Row
mDb.insert(DATABASE_TABLE_PROJ, null, values);
mDb.close(); // Closing database connection
}
public Cursor fetchAllProjects() {
// TODO Auto-generated method stub
return mDb.query(DATABASE_TABLE_PROJ, new String[] {CATEGORY_COLUMN_ID, CATEGORY_COLUMN_TITLE, CATEGORY_COLUMN_CONTENT, CATEGORY_COLUMN_COUNT }, null, null, null, null, null);
}
public GinfyDbAdapter(Context ctx) {
this.mCtx = ctx;
}
public GinfyDbAdapter open() throws SQLException {
mDbHelper = new DatabaseHelper(mCtx);
mDb = mDbHelper.getWritableDatabase();
return this;
}
}
this is my MainActivity.java
here only i mention my url of json also
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_item);
mDbHelper=new GinfyDbAdapter(MainActivity.this);
mDbHelper.open();
Cursor projectsCursor = mDbHelper.fetchAllProjects();
if(projectsCursor!=null)
{
fillData(projectsCursor);
Log.i("filling", "...");
}
else
{
new GetDataAsyncTask().execute();
}
//lv1 =(ListView)findViewById(R.id.list);
//lv =(ListView)findViewById(R.id.list);
btnGetSelected = (Button) findViewById(R.id.btnget);
btnGetSelected.setOnClickListener(this);
myFilter = (EditText) findViewById(R.id.myFilter);
//praycount.setOnClickListener(this);
//initView();
}
/*private void initView(){
// show progress dialog
dialog = ProgressDialog.show(this, "", "Loading...");
String url = "http://www.ginfy.com/api/v1/posts.json";
FetchDataTask task = new FetchDataTask(this);
task.execute(url);
} */
private class GetDataAsyncTask extends AsyncTask<Void, Void, Void> {
private ProgressDialog Dialog = new ProgressDialog(MainActivity.this);
protected void onPreExecute() {
Dialog.setMessage("Loading.....");
Dialog.show();
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
Dialog.dismiss();
Cursor projectsCursor = mDbHelper.fetchAllProjects();
if(projectsCursor!=null)
{
mDbHelper=new GinfyDbAdapter(MainActivity.this);
mDbHelper.open();
fillData(projectsCursor);
}
}
#Override
protected Void doInBackground(Void... params) {
getData();
return null;
}
}
public void getData() {
try
{
HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
HttpGet request = new HttpGet("https://ancient-caverns-4909.herokuapp.com/api/v1/posts.json");
// HttpGet request = new HttpGet("http://gdata.youtube.com/feeds/api/users/mbbangalore/uploads?v=2&alt=jsonc");
HttpResponse response = httpclient.execute(request);
HttpEntity resEntity = response.getEntity();
String _response=EntityUtils.toString(resEntity); // content will be consume only once
Log.i("................",_response);
httpclient.getConnectionManager().shutdown();
JSONObject jsonObject = new JSONObject(_response);
JSONArray contacts = jsonObject.getJSONArray("post");//(url);
for(int i = 0; i < contacts.length(); i++){
JSONObject c = contacts.getJSONObject(i);
String id = c.getString("id");
String title = c.getString("title");
String content = c.getString("content");
String count = c.getString("count");
mDbHelper=new GinfyDbAdapter(MainActivity.this);
mDbHelper.open();
mDbHelper.saveCategoryRecord(new Category(id,title,content,count));
}
} catch (Exception e) {
e.printStackTrace();
}
}
#SuppressLint("NewApi")
#SuppressWarnings("deprecation")
private void fillData(Cursor projectsCursor) {
//mDbHelper.open();
if(projectsCursor!=null)
{
String[] from = new String[]{GinfyDbAdapter.CATEGORY_COLUMN_TITLE, GinfyDbAdapter.CATEGORY_COLUMN_CONTENT, GinfyDbAdapter.CATEGORY_COLUMN_COUNT};
int[] to = new int[]{R.id.text2, R.id.text1, R.id.count};
dataAdapter = new SimpleCursorAdapter(
this, R.layout.activity_row,
projectsCursor,
from,
to,
0);
setListAdapter(dataAdapter);
}else
{
Log.i("...........","null");
}
}
My Database is not upgrading due to JSON change,it will take only one time of json data only.

Want to insert json data into the Sqlite Database

I want to store an json data to db,it has to display my apps has to display some previous data without internet time also.For that i want to create an db for json data to store.
This is the db part i created for json data.
public class GinfyDbAdapter {
private static final String DATABASE_NAME = "ginfy.db";
private static final String DATABASE_TABLE_PROJ = "prayers";
private static final int DATABASE_VERSION = 2;
public static final String CATEGORY_COLUMN_ID = "id";
public static final String CATEGORY_COLUMN_TITLE = "title";
public static final String CATEGORY_COLUMN_CONTENT = "content";
public static final String CATEGORY_COLUMN_COUNT = "count";
private static final String TAG = "ProjectDbAdapter";
private DatabaseHelper mDbHelper;
private SQLiteDatabase mDb;
public GinfyDbAdapter(MainActivity mainActivity) {
// TODO Auto-generated constructor stub
}
public GinfyDbAdapter GinfyDbAdapter(Context context){
mDbHelper = new DatabaseHelper(context);
mDb = mDbHelper.getWritableDatabase();
return this;
}
public void saveCategoryRecord(String id, String title, String content, String count) {
ContentValues contentValues = new ContentValues();
contentValues.put(CATEGORY_COLUMN_ID, id);
contentValues.put(CATEGORY_COLUMN_TITLE, title);
contentValues.put(CATEGORY_COLUMN_CONTENT, content);
contentValues.put(CATEGORY_COLUMN_COUNT, count);
mDb.insert(DATABASE_NAME, null, contentValues);
}
public Cursor getTimeRecordList() {
return mDb.rawQuery("select * from " + DATABASE_NAME, null);
}
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
private static final String DATABASE_CREATE_PROJ =
"create table " + DATABASE_TABLE_PROJ + " ("
+ CATEGORY_COLUMN_ID + " integer primary key autoincrement, "
+ CATEGORY_COLUMN_TITLE + " text not null, " + CATEGORY_COLUMN_CONTENT + " text not null, " + CATEGORY_COLUMN_COUNT + " integer primary key autoincrement );" ;
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL("CREATE TABLE " + DATABASE_TABLE_PROJ + "( "
+ CATEGORY_COLUMN_ID + " INTEGER PRIMARY KEY, "
+ CATEGORY_COLUMN_TITLE + " TEXT, " + CATEGORY_COLUMN_CONTENT + " TEXT, " + CATEGORY_COLUMN_COUNT + " INTEGER PRIMARY KEY )" );
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS"+ DATABASE_NAME);
onCreate(db);
}
}
}
this is mainactivity which is showing listview
public class MainActivity extends Activity implements FetchDataListener,OnClickListener{
private static final int ACTIVITY_CREATE=0;
private static final String TAG_CATEGORY = "post";
private static final String CATEGORY_COLUMN_ID = "id";
private static final String CATEGORY_COLUMN_TITLE = "title";
private static final String CATEGORY_COLUMN_CONTENT = "content";
private static final String CATEGORY_COLUMN_COUNT = "count";
private static final int Application = 0;
private ProgressDialog dialog;
ListView lv;
ListView lv1;
private List<Application> items;
private Button btnGetSelected;
private Button praycount;
public int pct;
private String stringVal;
private TextView value;
private int prayers;
private int prayerid;
EditText myFilter;
ApplicationAdapter adapter;
private GinfyDbAdapter mDbHelper;
JSONArray contacts = null;
private SimpleCursorAdapter dataAdapter;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_item);
mDbHelper=new GinfyDbAdapter(MainActivity.this);
lv1 =(ListView)findViewById(R.id.list);
lv =(ListView)findViewById(R.id.list);
ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();
// Creating JSON Parser instance
//JSONParser jParser = new JSONParser();
JSONObject jsonObject = new JSONObject();
//JSONArray aJson = jsonObject.getJSONArray("post");
String url = "http://www.ginfy.com/api/v1/posts.json";
// getting JSON string from URL
JSONArray aJson = jsonObject.getJSONFromUrl(url);
try {
// Getting Array of Contacts
contacts = aJson.getJSONObject(TAG_CATEGORY);
// looping through All Contacts
for(int i = 0; i < contacts.length(); i++){
JSONObject c = contacts.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(CATEGORY_COLUMN_ID);
String title = c.getString(CATEGORY_COLUMN_TITLE);
String content = c.getString(CATEGORY_COLUMN_CONTENT);
String count = c.getString(CATEGORY_COLUMN_COUNT);
mDbHelper.saveCategoryRecord(id,title,content,count);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(CATEGORY_COLUMN_ID, id);
map.put(CATEGORY_COLUMN_TITLE, title);
map.put(CATEGORY_COLUMN_CONTENT, content);
map.put(CATEGORY_COLUMN_COUNT, count);
// adding HashList to ArrayList
contactList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
btnGetSelected = (Button) findViewById(R.id.btnget);
btnGetSelected.setOnClickListener(this);
myFilter = (EditText) findViewById(R.id.myFilter);
//praycount.setOnClickListener(this);
initView();
}
private void initView(){
// show progress dialog
dialog = ProgressDialog.show(this, "", "Loading...");
String url = "http://www.ginfy.com/api/v1/posts.json";
FetchDataTask task = new FetchDataTask(this);
task.execute(url);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
MenuInflater mi = getMenuInflater();
mi.inflate(R.menu.activity_main, menu);
return true;
}
#Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
createProject();
return super.onMenuItemSelected(featureId, item);
}
private void createProject() {
Intent i = new Intent(this, AddPrayerActivity.class);
startActivityForResult(i, ACTIVITY_CREATE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
initView();
}
#Override
public void onFetchComplete(List<Application> data){
this.items = data;
// dismiss the progress dialog
if ( dialog != null )
dialog.dismiss();
// create new adapter
ApplicationAdapter adapter = new ApplicationAdapter(this, data);
/*dataAdapter adapter = new SimpleCursorAdapter(this,
R.layout.activity_row,
new String[] { CATEGORY_COLUMN_TITLE, CATEGORY_COLUMN_CONTENT, CATEGORY_COLUMN_COUNT }, new int[] {
R.id.text2, R.id.text1, R.id.count });*/
//lv.setListAdapter(adapter);
// set the adapter to list
lv.setAdapter(adapter);
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
CheckBox chk = (CheckBox) view.findViewById(R.id.checkbox);
Application bean = items.get(position);
if (bean.isSelected()) {
bean.setSelected(false);
chk.setChecked(false);
} else {
bean.setSelected(true);
chk.setChecked(true);
}
}
});
}
// Toast is here...
private void showToast(String msg) {
Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
}
#Override
public void onFetchFailure(String msg){
if ( dialog != null )
dialog.dismiss();
Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
}
Before using db it shows in listview also,rite now i want to make db also,for that i wrote some code in mainactivity.
Fetchdatatask.java
public class FetchDataTask extends AsyncTask<String, Void, String>
{
private final FetchDataListener listener;
private OnClickListener onClickListener;
private String msg;
public FetchDataTask(FetchDataListener listener)
{
this.listener = listener;
}
#Override
protected String doInBackground(String... params)
{
if ( params == null )
return null;
// get url from params
String url = params[0];
try
{
// create http connection
HttpClient client = new DefaultHttpClient();
HttpGet httpget = new HttpGet(url);
// connect
HttpResponse response = client.execute(httpget);
// get response
HttpEntity entity = response.getEntity();
if ( entity == null )
{
msg = "No response from server";
return null;
}
// get response content and convert it to json string
InputStream is = entity.getContent();
return streamToString(is);
}
catch ( IOException e )
{
msg = "No Network Connection";
}
return null;
}
#Override
protected void onPostExecute(String sJson)
{
if ( sJson == null )
{
if ( listener != null )
listener.onFetchFailure(msg);
return;
}
try
{
// convert json string to json object
JSONObject jsonObject = new JSONObject(sJson);
JSONArray aJson = jsonObject.getJSONArray("post");
// create apps list
List<Application> apps = new ArrayList<Application>();
for ( int i = 0; i < aJson.length(); i++ )
{
JSONObject json = aJson.getJSONObject(i);
Application app = new Application();
app.setContent(json.getString("content"));
app.setTitle(json.getString("title"));
app.setCount(Integer.parseInt(json.getString("count")));
app.setId(Integer.parseInt(json.getString("id")));
// add the app to apps list
apps.add(app);
}
//notify the activity that fetch data has been complete
if ( listener != null )
listener.onFetchComplete(apps);
}
catch ( JSONException e )
{
e.printStackTrace();
msg = "Invalid response";
if ( listener != null )
listener.onFetchFailure(msg);
return;
}
}
/**
* This function will convert response stream into json string
*
* #param is
* respons string
* #return json string
* #throws IOException
*/
public String streamToString(final InputStream is) throws IOException
{
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try
{
while ( (line = reader.readLine()) != null )
{
sb.append(line + "\n");
}
}
catch ( IOException e )
{
throw e;
}
finally
{
try
{
is.close();
}
catch ( IOException e )
{
throw e;
}
}
return sb.toString();
}
}
This fetchdatatask fetch from json and showing in listview,i want that without internet time it has to show in listview also for that i am creating db.
can you check my code is correct,actually it showing error in mainactivity line JSONArray aJson = jsonObject.getJSONFromUrl(url);
Create a class which act's as the intermediate between your Db class and the main activity to insert the data into the db and vice versa
public class Category {
String id;
String title;
String content;
String count;
public Category(String id, String title, String content, String count) {
super();
this.id = id;
this.title = title;
this.content = content;
this.count = count;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getCount() {
return count;
}
public void setCount(String count) {
this.count = count;
}
}
In your main activity where you do the json parsing create an object of DB class and call one the save record method at there like i did below
DatabaseHelper mDbHelper;
public class ABC extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.abc);
mDbHelper= new DatabaseHelper (this);
new GetSyncDataAsyncTask().execute();
}
}
private class GetDataAsyncTask extends AsyncTask<Void, Void, Boolean> {
private ProgressDialog Dialog = new ProgressDialog(ABC.this);
protected void onPreExecute() {
Dialog.setMessage("Loading.....");
Dialog.show();
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
Dialog.dismiss();
Intent intent = new Intent(ABC.this, XYZ.class);
startActivity(intent);
}
#Override
protected Boolean doInBackground(Void... params) {
getData();
return null;
}
}
public void getProdData() {
// getting JSON string from URL
JSONParser parser = new JSONParser();
JSONObject jsonObject = new JSONObject();
//JSONArray aJson = jsonObject.getJSONArray("post");
String url = "http://www.ginfy.com/api/v1/posts.json";
// getting JSON string from URL
JSONArray aJson = jsonObject.getJSONFromUrl(url);
try {
// Getting Array of Contacts
contacts = aJson.getJSONObject(TAG_CATEGORY);
// looping through All Contacts
for(int i = 0; i < contacts.length(); i++){
JSONObject c = contacts.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(CATEGORY_COLUMN_ID);
String title = c.getString(CATEGORY_COLUMN_TITLE);
String content = c.getString(CATEGORY_COLUMN_CONTENT);
String count = c.getString(CATEGORY_COLUMN_COUNT);
mDbHelper.saveCategoryRecord(new Category(id,title,content,count));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
At last in your db class insert the values like below
public void saveCategoryRecord(Category category) {
String query = "insert into"+ TABLE_NAME+ values( ?, ?, ?, ?, ?, ? )";
SQLiteStatement stmt = mDb.compileStatement(query);
stmt.bindString(1, category.getId());
stmt.bindString(2, category.getTitle());
stmt.bindString(3, category.getContent());
stmt.bindString(4, category.getCount());
stmt.execute();
}
I have tried to use the same things as you have used. This is the way i think now you got the concept to do that

Categories