How strart method execution after one method finished executing - java

im making simple notes app width Sqlite Mysql sync. The problem is that when i save my data in edit_note_fragment and then go back to fragment width my recyclerView my list don't load new data. It's because String request take a while to perform and saves data after my list is already refreshed in my recyclerView. I already tried to delay the refresh but the ansfer from server sometimes takes longer and the same thing happen. Any idea how execute refresh after the data was saved? Here is my code
edit note fragment
buttonBack.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (StringId != null) {
UpdateNote();
}else { CreateNote(); }
Fragment fragment = new NotesFragment();
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.frameLayoutHome, fragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
});
}
private void CreateNote() {
final String name = EtTitle.getText().toString().trim();
final String des = EtDes.getText().toString().trim();
StringRequest stringRequest = new StringRequest(Request.Method.POST, Api.URL_CREATE_IVDATA,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject obj = new JSONObject(response);
if (!obj.getBoolean("error")) {
//if there is a success
Log.d(TAG, "Created");
//storing the name to sqlite with status synced
JSONArray ivdata = (obj.getJSONArray("ivdata"));
for (int i = 0; i < ivdata.length(); i++) {
JSONObject json = ivdata.getJSONObject(i);
int serverId = json.getInt("sid");
String StringSid = String.valueOf(serverId);
saveNameToLocalStorage(name, des, NAME_SYNCED_WITH_SERVER, StringSid);
}
} else {
//if there is some error
//saving the name to sqlite with status unsynced
saveNameToLocalStorage(name, des, NAME_NOT_SYNCED_WITH_SERVER, null);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
saveNameToLocalStorage(name, des, NAME_NOT_SYNCED_WITH_SERVER, null);
Log.d(TAG, "saving to local storage");
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("t1", myToken);
params.put("t2", "notes");
params.put("c1", name);
params.put("c2", des);
return params;
}
};
VolleySingleton.getInstance(context).addToRequestQueue(stringRequest);
}
private void saveNameToLocalStorage(String name,String des, int status, String sid) {
mDatabase.addNote(name, des, status, sid);
Note n = new Note(name,des, status, sid);
noteList.add(n);
}
fragment width my recyclerview(refresh is in executed in onViewCreated)
private void refresh()
{
noteList.clear();
mDatabase = new SqliteDatabase(context);
noteList = mDatabase.listContacts();
Log.d(TAG, "refreshing");
if(!(noteList.size()<1))
{
notesAdapter = new NotesAdapter(noteList, context, this);
recyclerView.setAdapter(notesAdapter);
} else {
recyclerView.setVisibility(View.GONE);
Toast.makeText(context, "There is no Notes in the database. Start adding now", Toast.LENGTH_LONG).show();
}
}
SqliteDatabaseHelper
public ArrayList<Note> listContacts() {
String sql = "select * from " + TABLE_NAME;
SQLiteDatabase db = this.getReadableDatabase();
ArrayList<Note> noteList= new ArrayList<>();
Cursor cursor = db.rawQuery(sql, null);
if (cursor.moveToFirst()) {
do {
int id = Integer.parseInt(cursor.getString(0));
String c1 = cursor.getString(1);
String c2 = cursor.getString(2);
int status = Integer.parseInt(cursor.getString(3));
String sid = cursor.getString(4);
noteList.add(new Note(id, c1, c2, status, sid));
}
while (cursor.moveToNext());
}
cursor.close();
return noteList;
}
public boolean addNote(String name,String des, int status, String sid) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COLUMN_NAME, name);
contentValues.put(COLUMN_DESC, des);
contentValues.put(COLUMN_STATUS, status);
contentValues.put(COLUMN_SID, sid);
db.insert(TABLE_NAME, null, contentValues);
db.close();
return true;
}

you can set a listener on the update of the DB. When the callback get called you refresh the list. (If I understood the problem correctly lol)
SQLITE DB UPDATE CALLBACKS

Related

Android studio: I am trying to change the shared preferences and want to store the data in the SQLite database [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I am new in Java Programming.
Now, I am facing the problem that I want to change the shared preferences and want to use the SQLite database to store these data. I had created the table for store these data and I am trying to save these data in SQLite.
How can I do? Anyone can help me ????
MyDatabase-Table
This is my code that using shared preferences :
public class Login extends AppCompatActivity {
InputStream inputStream;
ACDatabase db;
SharedPreferences prefs;
ActivityLoginBinding binding;
AC_Class.Connection connection;
AC_Class.Register reg;
String versionNo;
String url;
String urlStr;
String id;
String pwd;
private static String uniqueID = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
binding = DataBindingUtil.setContentView(this, R.layout.activity_login);
getSupportActionBar().hide();
// Placeholder
versionNo = "3.1.6";
reg = new AC_Class.Register();
connection = new AC_Class.Connection();
binding.setConSettings(connection);
db = new ACDatabase(this);
// Check preferences/create if nonexistent
prefs = this.getSharedPreferences("com.presoft.androidmobilestock", Context.MODE_PRIVATE);
uniqueID = prefs.getString("UUID", null);
if (uniqueID == null)
{
uniqueID = UUID.randomUUID().toString();
//uniqueID = "3FDE9813F93A47CBA6CD4F5DAAECEE01";
prefs.edit().putString("UUID", uniqueID).commit();
}
binding.lblUUID.setText(uniqueID);
binding.lblVersion.setText(versionNo);
if (prefs.getString("ID", id) != null) {
binding.rmbCheckBox.setChecked(true);
url = prefs.getString("URL", url);
binding.txtURL.setText(prefs.getString("URLstr", urlStr));
binding.txtID.setText(prefs.getString("ID", id));
binding.txtpw.setText(prefs.getString("pwd", pwd));
}
if (prefs.getString("Default_curr", null) == null) {
prefs.edit().putString("Default_curr", "RM").apply();
}
if (prefs.getString("Default_loc", null) == null) {
Cursor tempCursor = db.getLocation();
if (tempCursor.moveToNext()) {
prefs.edit().putString("Default_loc", tempCursor
.getString(tempCursor.getColumnIndex("Location"))).apply();
}
}
// Version number
if (prefs.getString("Version ", null) == null) {
prefs.edit().putString("Version", versionNo).apply();
}
// Tax Inclusive
if (!prefs.getBoolean("taxInclusive", false)) {
prefs.edit().putBoolean("taxInclusive", false).apply();
}
if (Build.MODEL.equals("HC720"))
{
Snackbar.make(findViewById(android.R.id.content), "RFID Detected.", Snackbar.LENGTH_SHORT).show();
}
}
#Override
public void onBackPressed() {
finish();
}
//On return of intent
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == 7) {
url = data.getStringExtra("URLKey");
urlStr = data.getStringExtra("URLStr");
Log.i("custDebug", url + ", " + urlStr);
binding.txtURL.setText(urlStr);
if (!TextUtils.isEmpty(binding.txtURL.getText().toString())) {
new GetModules(Login.this).execute(url);
new GetLoginList(Login.this).execute(url);
new SetDevice(Login.this).execute(url);
}
}
}
//Open connection settings
public void btnSetClicked(View view) {
Intent intent = new Intent(Login.this, ConnectionSettings.class);
startActivityForResult(intent, 7);
}
//Reset Database
public void btnResetDbClicked(final View view) {
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Reset DB");
builder.setMessage("Are you sure you want to reset the Database?");
final EditText input = new EditText(this);
input.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
builder.setView(input);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (input.getText().toString().equals("presoftmobile")) {
db.close();
deleteDatabase("AutoCountDatabase");
} else {
// Toast.makeText(getApplicationContext(), "Incorrect Password", Toast.LENGTH_SHORT);
}
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
}
//Login button
public void btnLoginBtnClicked(View view) {
if (TextUtils.isEmpty(binding.txtURL.getText().toString())) {
binding.txtURL.setError("This field can't be blank.");
//return;
}
if (TextUtils.isEmpty(binding.txtID.getText().toString())) {
binding.txtID.setError("This field can't be blank.");
//return;
}
if (TextUtils.isEmpty(binding.txtpw.getText().toString())) {
binding.txtpw.setError("This field can't be blank.");
//return;
}
//Non-empty fields
else {
Cursor checkData = db.loginValidate(binding.txtID.getText().toString(),
binding.txtpw.getText().toString().toUpperCase());
if (checkData.getCount() > 0) {
checkData.moveToNext();
//Shared Preferences
prefs.edit().putString("URL", url).apply();
prefs.edit().putString("URLstr", binding.txtURL.getText().toString()).apply();
if (binding.rmbCheckBox.isChecked()) {
prefs.edit().putString("ID", binding.txtID.getText().toString()).apply();
prefs.edit().putString("pwd", binding.txtpw.getText().toString()).apply();
}
prefs.edit().putInt("EnableSetting", checkData.getInt(checkData.getColumnIndex("EnableSetting"))).apply();
prefs.edit().putInt("FilterByAgent", checkData.getInt(checkData.getColumnIndex("FilterByAgent"))).apply();
prefs.edit().putInt("Sales", checkData.getInt(checkData.getColumnIndex("Sales"))).apply();
prefs.edit().putInt("Purchase", checkData.getInt(checkData.getColumnIndex("Purchase"))).apply();
prefs.edit().putInt("Transfer", checkData.getInt(checkData.getColumnIndex("Transfer"))).apply();
if (url != null) {
try {
// Check Connection
new SetDevice(Login.this).execute(url);
// Go to main
Intent intent = new Intent(Login.this, Dashboard.class);
intent.putExtra("URLKey", url);
intent.putExtra("URLStr", binding.txtURL.getText().toString());
startActivity(intent);
finish();
} catch (Exception e) {
Log.i("custDebug", e.getMessage());
Toast.makeText(this, "Unable to connect to server", Toast.LENGTH_SHORT).show();
}
}
} else {
Toast.makeText(this, "Invalid login credentials", Toast.LENGTH_SHORT).show();
binding.txtpw.setText(null);
}
checkData.close();
}
}
This is the code that to save the data in SQLite database (but getting error):
public class Login extends AppCompatActivity {
InputStream inputStream;
ACDatabase db;
SharedPreferences prefs;
ActivityLoginBinding binding;
AC_Class.Connection connection;
AC_Class.Register reg;
String versionNo;
String url;
String urlStr;
String id;
String pwd;
private static String uniqueID = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
binding = DataBindingUtil.setContentView(this, R.layout.activity_login);
getSupportActionBar().hide();
// Placeholder
versionNo = "3.1.6";
connection = new AC_Class.Connection();
binding.setConSettings(connection);
db = new ACDatabase(this);
db = new ACDatabase(this);
uniqueID = db.getReg("8");
uniqueID = prefs.getString("UUID", null);
if (uniqueID == null)
{
uniqueID = UUID.randomUUID().toString();
//uniqueID = "3FDE9813F93A47CBA6CD4F5DAAECEE01";
db.updateREG("8", uniqueID);
}
binding.lblUUID.setText(uniqueID);
binding.lblVersion.setText(versionNo);
if (prefs.getString("ID", id) != null) {
binding.rmbCheckBox.setChecked(true);
url = prefs.getString("URL", url);
binding.txtURL.setText(prefs.getString("URLstr", urlStr));
binding.txtID.setText(prefs.getString("ID", id));
binding.txtpw.setText(prefs.getString("pwd", pwd));
}
if (prefs.getString("Default_curr", null) == null) {
prefs.edit().putString("Default_curr", "RM").apply();
}
if (prefs.getString("Default_loc", null) == null) {
Cursor tempCursor = db.getLocation();
if (tempCursor.moveToNext()) {
prefs.edit().putString("Default_loc", tempCursor
.getString(tempCursor.getColumnIndex("Location"))).apply();
}
}
// Version number
if (prefs.getString("Version ", null) == null) {
prefs.edit().putString("Version", versionNo).apply();
}
// Tax Inclusive
if (!prefs.getBoolean("taxInclusive", false)) {
prefs.edit().putBoolean("taxInclusive", false).apply();
}
if (Build.MODEL.equals("HC720"))
{
Snackbar.make(findViewById(android.R.id.content), "RFID Detected.", Snackbar.LENGTH_SHORT).show();
}
}
mydatabasehelper
//GET value by id
public Cursor getReg(String id) {
SQLiteDatabase db = this.getWritableDatabase();
Cursor data = db.rawQuery("SELECT Value FROM " + TABLE_NAME_REG + " WHERE ID ='" + id + "'",null);
return data;
}
//update value
public boolean updateREG(String ID, String Value) {
SQLiteDatabase database = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put("Value", Value);
String[] args = new String[]{ID};
database.update("Reg", cv, "ID = ?", args);
return true;
}
The following is a working example that acts very similar to shared prefs but stores the prefs in an SQLite database.
The table is very simple 2 columns. The key (name of the stored value) and the value itself. Which can be String, boolean, int, long or Float.
It includes methods to; insert (add) a key/value pair, update a key/value pair and to get a value according to the key and also to return a default value as passed (making it easy to detect if the value was retrieved).
The DatabaseHelper (sub class of SQLiteOpenHelper) has most of the code and is :-
class DBHelper extends SQLiteOpenHelper {
private static volatile DBHelper instance = null;
private SQLiteDatabase db = null;
public static final String DBNAME = "sharedpreferences.db";
public static final int DBVERSION = 1;
public static final String TBLNAME_SP = "_shared_preferences";
public static final String COLNAME_SP_KEY = "_key";
public static final String COLNAME_SP_VALUE = "_value";
private DBHelper(#Nullable Context context) {
super(context, DBNAME, null, DBVERSION);
db = this.getWritableDatabase();
}
public static DBHelper getInstance(Context context) {
if (instance == null) {
instance = new DBHelper(context);
}
return instance;
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE IF NOT EXISTS " + TBLNAME_SP +
"(" +
COLNAME_SP_KEY + " PRIMARY KEY," +
COLNAME_SP_VALUE + " TEXT" +
")");
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
}
private long insertPrefsRow(ContentValues cv, String key) {
cv.put(COLNAME_SP_KEY,key);
return db.insertWithOnConflict(TBLNAME_SP,null,cv, SQLiteDatabase.CONFLICT_IGNORE);
}
public long insertPrefsValue (String key, int value) {
ContentValues cv = new ContentValues();
cv.put(COLNAME_SP_VALUE,value);
return insertPrefsRow(cv,key);
}
public long insertPrefsValue (String key, String value) {
ContentValues cv = new ContentValues();
cv.put(COLNAME_SP_VALUE,value);
return insertPrefsRow(cv,key);
}
public long insertPrefsValue (String key, long value) {
ContentValues cv = new ContentValues();
cv.put(COLNAME_SP_VALUE,value);
return insertPrefsRow(cv,key);
}
public long insertPrefsValue (String key, boolean value) {
ContentValues cv = new ContentValues();
cv.put(COLNAME_SP_VALUE,value);
return insertPrefsRow(cv,key);
}
public long insertPrefsValue (String key, float value) {
ContentValues cv = new ContentValues();
cv.put(COLNAME_SP_VALUE,value);
return insertPrefsRow(cv,key);
}
private long updatePrefs(String key, ContentValues cv) {
return db.update(TBLNAME_SP,cv,COLNAME_SP_KEY + "=?",new String[]{key} );
}
public long updatePrefsStringValue(String key, String newValue) {
ContentValues cv = new ContentValues();
cv.put(COLNAME_SP_VALUE,newValue);
return updatePrefs(key,cv);
}
public long updatePrefsStringValue(String key, boolean newValue) {
ContentValues cv = new ContentValues();
cv.put(COLNAME_SP_VALUE,newValue);
return updatePrefs(key,cv);
}
public long updatePrefsStringValue(String key, int newValue) {
ContentValues cv = new ContentValues();
cv.put(COLNAME_SP_VALUE,newValue);
return updatePrefs(key,cv);
}
public long updatePrefsStringValue(String key, long newValue) {
ContentValues cv = new ContentValues();
cv.put(COLNAME_SP_VALUE,newValue);
return updatePrefs(key,cv);
}
public long updatePrefsStringValue(String key, Float newValue) {
ContentValues cv = new ContentValues();
cv.put(COLNAME_SP_VALUE,newValue);
return updatePrefs(key,cv);
}
private Cursor getPrefsValue(String key) {
return db.query(TBLNAME_SP,new String[]{COLNAME_SP_VALUE},COLNAME_SP_KEY + "=?",new String[]{key},null,null,null);
}
public String getPrefsStringValue(String key, String default_value) {
String rv = default_value;
Cursor csr;
if ((csr = getPrefsValue(key)).moveToFirst()) {
rv = csr.getString(csr.getColumnIndex(COLNAME_SP_VALUE));
csr.close();
}
return rv;
}
public Boolean getPrefsBooleanValue(String key, boolean default_value ) {
Boolean rv = default_value;
Cursor csr;
if ((csr = getPrefsValue(key)).moveToFirst()) {
rv = csr.getInt(csr.getColumnIndex(COLNAME_SP_VALUE)) != 0;
csr.close();
}
return rv;
}
public int getPrefsIntValue(String key, int default_value) {
int rv = default_value;
Cursor csr;
if ((csr = getPrefsValue(key)).moveToFirst()) {
rv = csr.getInt(csr.getColumnIndex(COLNAME_SP_VALUE));
csr.close();
}
return rv;
}
public long getPrefsLongValue(String key, long default_value) {
long rv = default_value;
Cursor csr;
if ((csr = getPrefsValue(key)).moveToFirst()) {
rv = csr.getLong(csr.getColumnIndex(COLNAME_SP_VALUE));
csr.close();
}
return rv;
}
public Float getPrefsFLoatValue(String key, Float default_value) {
Float rv = default_value;
Cursor csr;
if ((csr = getPrefsValue(key)).moveToFirst()) {
rv = csr.getFloat(csr.getColumnIndex(COLNAME_SP_VALUE));
csr.close();
}
return rv;
}
}
The following is an activity that demonstrates usage:-
public class MainActivity extends AppCompatActivity {
DBHelper db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
db = DBHelper.getInstance(this);
db.insertPrefsValue("UUID","3FDE9813F93A47CBA6CD4F5DAAECEE01");
db.insertPrefsValue("taxInclusive",false);
db.insertPrefsValue("myprefs_int",100);
db.insertPrefsValue("myprefs_long",100L);
db.insertPrefsValue("myprefs_float",10.567F);
Log.d("PREFSINFO",
"Stored UUID is " + db.getPrefsStringValue("UUID","000000000000000000000000") +
" Stored taxinclusive is " + db.getPrefsBooleanValue("taxInclusive",true) +
" Stored mpint is " + db.getPrefsIntValue("myprefs_int",-99) +
" Stored mplong is " + db.getPrefsLongValue("myprefs_long",-99999999) +
" Stored mpfloat is " + db.getPrefsFLoatValue("myprefs_float",-999999.999999F) +
" NOT STORED is " + db.getPrefsFLoatValue("NOT A SET KEY",-3333.3333F)
);
db.updatePrefsStringValue("UUID","FFFF9813F93A47CBA6CD4F5DAAECEE01");
Log.d("PREFSINFO",
"Stored UUID is " + db.getPrefsStringValue("UUID","000000000000000000000000") +
" Stored taxinclusive is " + db.getPrefsBooleanValue("taxInclusive",true) +
" Stored mpint is " + db.getPrefsIntValue("myprefs_int",-99) +
" Stored mplong is " + db.getPrefsLongValue("myprefs_long",-99999999) +
" Stored mpfloat is " + db.getPrefsFLoatValue("myprefs_float",-999999.999999F) +
" NOT STORED is " + db.getPrefsFLoatValue("NOT A SET KEY",-3333.3333F)
);
}
}
When run (or rerun BUT when rerun the updated UUID rather than the original is retrieved) the log contains :-
D/PREFSINFO: Stored UUID is 3FDE9813F93A47CBA6CD4F5DAAECEE01 Stored taxinclusive is false Stored mpint is 100 Stored mplong is 100 Stored mpfloat is 10.567 NOT STORED is -3333.3333
D/PREFSINFO: Stored UUID is FFFF9813F93A47CBA6CD4F5DAAECEE01 Stored taxinclusive is false Stored mpint is 100 Stored mplong is 100 Stored mpfloat is 10.567 NOT STORED is -3333.3333
NOT STORED demonstrates the default value being returned when the Key/Name isn't stored.
As you can see UUID has been updated in the second line (if rerun both lines would show the updated value)

how to get the items name from listview after using intent with sqlite?

i have two listviews each one of them is in different activity i want to send an item from the first listview to the other one by long click on it im using intent, im using string file to get the data it sends the item perfectly but its not saved to sqlite i dont know where is the problem please take a look at my code
First Activity(Main Activity):
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long l) {
Intent intent = new Intent(MainActivity.this, cc.class);
intent.putExtra("EXTRAKEY_ID",l);// THIS ADDED
startActivity(intent);
fav_name = getAllDataInCurrentLocale.getString(getAllDataInCurrentLocale.getColumnIndex(FAVOURITES_COL_NAME));
Toast.makeText(MainActivity.this, fav_name+" Added To Favorite", Toast.LENGTH_SHORT).show();
return true;
}
});
Second Activity(cc):
fav_id = getIntent().getLongExtra("EXTRAKEY_ID", 0);
manageFavouritesListView();
if (fav_id==0){
}
getDataInCurrentLocaleById = dbSqlite.getDataInCurrentLocaleById(this,fav_id);
if (getDataInCurrentLocaleById.moveToFirst()) {
fav_name = getDataInCurrentLocaleById.getString(getDataInCurrentLocaleById.getColumnIndex(FAVOURITES_COL_NAME));
}
getDataInCurrentLocaleById.close();
}
private void manageFavouritesListView() {
getDataInCurrentLocaleById = dbSqlite.getDataInCurrentLocaleById(this,fav_id);
if (favourites_adapter == null) {
favourites_adapter = new SimpleCursorAdapter(
this,
R.layout.textview2,
getDataInCurrentLocaleById,
new String[]{FAVOURITES_COL_NAME},
new int[]{R.id.textview10},
0
);
listView.setAdapter(favourites_adapter);
setListViewHandler(listView, true);
} else {
favourites_adapter.swapCursor(getDataInCurrentLocaleById);
}
}
Db_Sqlite:
public Cursor getAllDataInCurrentLocale(Context context) {
SQLiteDatabase db = this.getWritableDatabase();
Cursor csr = db.query(TABLE_FAVOURITES,null,null,null,null,null,null);
if (csr.getCount() < 1) return csr;
MatrixCursor mxcsr = new MatrixCursor(csr.getColumnNames(),csr.getCount());
while (csr.moveToNext()) {
mxcsr.addRow(convertCursorRow(context,csr,new String[]{FAVOURITES_COL_NAME}));
}
csr.close();
return mxcsr;
}
public Cursor getDataInCurrentLocaleById(Context context, long id) {
SQLiteDatabase db = this.getWritableDatabase();
String wherepart = FAVOURITES_COL_ID + "=?";
String[] args = new String[]{String.valueOf(id)};
Cursor csr = db.query(TABLE_FAVOURITES,null,wherepart,args,null,null,null);
if (csr.getCount() < 1) return csr;
MatrixCursor mxcsr = new MatrixCursor(csr.getColumnNames(),csr.getCount());
while (csr.moveToNext()) {
mxcsr.addRow(convertCursorRow(context,csr,new String[]{FAVOURITES_COL_NAME}));
}
csr.close();
return mxcsr;
}
/* This getting columns from Cursor into String array (no BLOB handleing)*/
public String[] convertCursorRow(Context context, Cursor csr, String[] columnsToConvert) {
String[] rv = new String[csr.getColumnCount()];
for (String s: csr.getColumnNames()) {
boolean converted = false;
for (String ctc: columnsToConvert) {
if (csr.getType(csr.getColumnIndex(s)) == Cursor.FIELD_TYPE_BLOB) {
//........ would have to handle BLOB here if needed (another question if needed)
}
if (ctc.equals(s)) {
rv[csr.getColumnIndex(s)] = StringResourcesHandling.getStringByName(context,csr.getString(csr.getColumnIndex(s)));
converted = true;
}
} if (!converted) {
rv[csr.getColumnIndex(s)] = csr.getString(csr.getColumnIndex(s));
}
}
return rv;
}
}
i dont where is the problem please help me thank you in advance
You should notify the adapter that data changed.
private void manageFavouritesListView() {
getDataInCurrentLocaleById = dbSqlite.getDataInCurrentLocaleById(this,fav_id);
if (favourites_adapter == null) {
favourites_adapter = new SimpleCursorAdapter(
this,
R.layout.textview2,
getDataInCurrentLocaleById,
new String[]{FAVOURITES_COL_NAME},
new int[]{R.id.textview10},
0
);
listView.setAdapter(favourites_adapter);
favourites_adapter.notifyDataSetChanged();
setListViewHandler(listView, true);
} else {
favourites_adapter.swapCursor(getDataInCurrentLocaleById);
}
}

pass data from one activity to another and save it

i have two activities, each one have a listview. The first one contain the data and i want the other one to be as a favorite list. Right now i can pass the data with intent but its not saving. it shows when i start the intent but when i exit the second activity and go back to it with a custom button nothing is saved in the listview. Please tell me what to do. here is my code
public class MainActivity extends AppCompatActivity {
DB_Sqlite dbSqlite;
ListView listView;
String fav_name;
long fav_id;
ArrayAdapter adapter;
ArrayList arrayList;
String[] number;
Button button;
StringResourcesHandling srh;
Cursor getAllDataInCurrentLocale,getDataInCurrentLocaleById;
SimpleCursorAdapter favourites_adapter,non_favourites_adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.list_view);
SharedPreferences mPrefs = getPreferences(MODE_PRIVATE);
arrayList = new ArrayList<String>();
listView.setAdapter(adapter);
button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, cc.class);
startActivity(intent);
}
});
/* Show the resources for demo */
for (String s : StringResourcesHandling.getAllStringResourceNames()) {
Log.d("RESOURCEDATA", "String Resource Name = " + s +
"\n\tValue = " + StringResourcesHandling.getStringByName(this, s)
);
}
dbSqlite = new DB_Sqlite(this);
Cursor csr = dbSqlite.getAllDataInCurrentLocale(this);
DatabaseUtils.dumpCursor(csr);
csr.close();
}
#Override
protected void onDestroy() {
super.onDestroy();
getAllDataInCurrentLocale.close();
}
#Override
protected void onResume() {
super.onResume();
manageNonFavouritesListView();
}
private void manageNonFavouritesListView() {
getAllDataInCurrentLocale = dbSqlite.getAllDataInCurrentLocale(this);
if (non_favourites_adapter == null) {
non_favourites_adapter = new SimpleCursorAdapter(
this,
R.layout.textview,
getAllDataInCurrentLocale,
new String[]{FAVOURITES_COL_NAME},
new int[]{R.id.textview10},
0
);
listView.setAdapter(non_favourites_adapter);
setListViewHandler(listView,false);
} else {
non_favourites_adapter.swapCursor(getAllDataInCurrentLocale);
}
}
private void setListViewHandler(ListView listView, boolean favourite_flag) {
if (!favourite_flag) {
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
if (i == 0) {
Intent intent = new Intent(MainActivity.this,tc.class);
startActivity(intent);
}
if (i == 1) {
Intent intent = new Intent(MainActivity.this,vc.class);
startActivity(intent);
}
}
});
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long l) {
if (position == 0) {
Intent intent = new Intent(MainActivity.this, cc.class);
intent.putExtra("EXTRAKEY_ID",l); // THIS ADDED
startActivity(intent);}
String name = getAllDataInCurrentLocale.getString(getAllDataInCurrentLocale.getColumnIndex(FAVOURITES_COL_NAME));
Toast.makeText(MainActivity.this, name+" Added To Favorite", Toast.LENGTH_SHORT).show();
return true;
}
});
}}
}
public class DB_Sqlite extends SQLiteOpenHelper {
public static final String BDname = "data.db";
public static final int DBVERSION = 1; /*<<<<< ADDED BUT NOT NEEDED */
public static final String TABLE_FAVOURITES = "mytable";
public static final String FAVOURITES_COL_ID = BaseColumns._ID; /*<<<< use the Android stock ID name*/
public static final String FAVOURITES_COL_NAME = "name";
public static final String FAVOURITES_COL_FAVOURITEFLAG = "favourite_flag"; /*<<<<< NEW COLUMN */
public DB_Sqlite(#Nullable Context context) {
super(context, BDname, null, DBVERSION /*<<<<< used constant above */);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + TABLE_FAVOURITES + " (" +
FAVOURITES_COL_ID + " INTEGER PRIMARY KEY," + /*<<<<< AUTOINCREMENT NOT NEEDED AND IS INEFFICIENT */
FAVOURITES_COL_NAME + " TEXT, " +
FAVOURITES_COL_FAVOURITEFLAG + " INTEGER DEFAULT 0" + /*<<<<< COLUMN ADDED */
")");
/* CHANGES HERE BELOW loop adding all Resource names NOT VALUES */
ContentValues cv = new ContentValues();
for (String s: StringResourcesHandling.getAllStringResourceNames()) {
cv.clear();
cv.put(FAVOURITES_COL_NAME,s);
db.insert(TABLE_FAVOURITES,null,cv);
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_FAVOURITES);
onCreate(db);
}
public boolean insertData(String name){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(FAVOURITES_COL_NAME, name);
long result = db.insert(TABLE_FAVOURITES,null, contentValues);
if (result == -1)
return false;
else
return true;
}
public Cursor getFavouriteRows(boolean favourites) {
SQLiteDatabase db = this.getWritableDatabase();
String whereclause = FAVOURITES_COL_FAVOURITEFLAG + "=?";
String compare = "<1";
if (favourites) {
compare =">0";
}
return db.query(
TABLE_FAVOURITES,null,
FAVOURITES_COL_FAVOURITEFLAG + compare,
null,null,null,null
);
}
private int setFavourite(long id, boolean favourite_flag) {
SQLiteDatabase db = this.getWritableDatabase();
String whereclause = FAVOURITES_COL_ID + "=?";
String[] whereargs = new String[]{String.valueOf(id)};
ContentValues cv = new ContentValues();
cv.put(FAVOURITES_COL_FAVOURITEFLAG,favourite_flag);
return db.update(TABLE_FAVOURITES,cv,whereclause,whereargs);
}
public int setAsFavourite(long id) {
return setFavourite(id,true);
}
public int setAsNotFavourite(long id) {
return setFavourite(id, false);
}
/* Getting everything and make MatrixCursor VALUES from Resource names from Cursor with Resource names */
public Cursor getAllDataInCurrentLocale(Context context) {
SQLiteDatabase db = this.getWritableDatabase();
Cursor csr = db.query(TABLE_FAVOURITES,null,null,null,null,null,null);
if (csr.getCount() < 1) return csr;
MatrixCursor mxcsr = new MatrixCursor(csr.getColumnNames(),csr.getCount());
while (csr.moveToNext()) {
mxcsr.addRow(convertCursorRow(context,csr,new String[]{FAVOURITES_COL_NAME}));
}
csr.close();
return mxcsr;
}
public Cursor getDataInCurrentLocaleById(Context context, long id) {
SQLiteDatabase db = this.getWritableDatabase();
String wherepart = FAVOURITES_COL_ID + "=?";
String[] args = new String[]{String.valueOf(id)};
Cursor csr = db.query(TABLE_FAVOURITES,null,wherepart,args,null,null,null);
if (csr.getCount() < 1) return csr;
MatrixCursor mxcsr = new MatrixCursor(csr.getColumnNames(),csr.getCount());
while (csr.moveToNext()) {
mxcsr.addRow(convertCursorRow(context,csr,new String[]{FAVOURITES_COL_NAME}));
}
csr.close();
return mxcsr;
}
/* This getting columns from Cursor into String array (no BLOB handleing)*/
private String[] convertCursorRow(Context context, Cursor csr, String[] columnsToConvert) {
String[] rv = new String[csr.getColumnCount()];
for (String s: csr.getColumnNames()) {
boolean converted = false;
for (String ctc: columnsToConvert) {
if (csr.getType(csr.getColumnIndex(s)) == Cursor.FIELD_TYPE_BLOB) {
//........ would have to handle BLOB here if needed (another question if needed)
}
if (ctc.equals(s)) {
rv[csr.getColumnIndex(s)] = StringResourcesHandling.getStringByName(context,csr.getString(csr.getColumnIndex(s)));
converted = true;
}
} if (!converted) {
rv[csr.getColumnIndex(s)] = csr.getString(csr.getColumnIndex(s));
}
}
return rv;
}
}
public class cc extends AppCompatActivity {
String fav_name;
long fav_id;
DB_Sqlite dbSqlite;
SimpleCursorAdapter favourites_adapter;
ListView listView1;
ArrayList<String> arrayList1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cc);
listView1 = (ListView) findViewById(R.id.list_view1);
arrayList1 = new ArrayList<String>();
fav_id = getIntent().getLongExtra("EXTRAKEY_ID", 0);
if (fav_id == 0) {
}
dbSqlite = new DB_Sqlite(this);
Cursor cursor = dbSqlite.getDataInCurrentLocaleById(this, fav_id);
if (cursor.moveToFirst()) {
fav_name = cursor.getString(cursor.getColumnIndex(FAVOURITES_COL_NAME));
manageNonFavouritesListView();
}
cursor.close();
}
private void manageNonFavouritesListView() {
Cursor cursor = dbSqlite.getDataInCurrentLocaleById(this,fav_id);
if (favourites_adapter == null) {
favourites_adapter = new SimpleCursorAdapter(
this,
R.layout.textview,
cursor,
new String[]{FAVOURITES_COL_NAME},
new int[]{R.id.textview10},
0
);
listView1.setAdapter(favourites_adapter);
setListViewHandler(listView1,true);
} else {
favourites_adapter.swapCursor(cursor);
}
}
private void setListViewHandler(ListView listView1, boolean b) {
listView1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
if (fav_id == 1) {
Intent intent = new Intent(cc.this, tc.class);
startActivity(intent);
}
if (fav_id == 2) {
Intent intent = new Intent(cc.this, vc.class);
startActivity(intent);
}
}
});
}
}
public class StringResourcesHandling {
private static final String[] allowedStringResourcePrefixes = new String[]{"db_"};
private static boolean loaded = false;
private static Field[] fields = R.string.class.getFields();
private static ArrayList<String> allowedStringResourceNames = new ArrayList<>();
private static void loadStringResources() {
if (loaded) return;
for (Field f: fields) {
if (isResourceNameAllowedPrefix(f.getName())) {
allowedStringResourceNames.add(f.getName());
}
}
loaded = true;
}
private static boolean isResourceNameAllowedPrefix(String resourceName) {
if (allowedStringResourcePrefixes.length < 1) return true;
for (String s: allowedStringResourcePrefixes) {
if (resourceName.substring(0,s.length()).equals(s)) return true;
}
return false;
}
public static String getStringByName(Context context, String name) {
String rv = "";
boolean nameFound = false;
if (!loaded) {
loadStringResources();
}
for (String s: allowedStringResourceNames) {
if (s.equals(name)) {
nameFound = true;
break;
}
}
if (!nameFound) return rv;
return context.getString(context.getResources().getIdentifier(name,"string",context.getPackageName()));
}
public static List<String> getAllStringResourceNames() {
if (!loaded) {
loadStringResources();
}
return allowedStringResourceNames;
}
}
note: i get the data in 1st listview from strings.xml
please help me thank u in advance
You can add a column say 'isFavourite' in your db table which has list vew data. When user mark listitem as favourite, save the change in db table . When user navigates to favourite list populate the list from. db table with favourite filter in select query.
I suggest using SharedPreferences. You stated that your value gets overwritten. That won't be the case if you create multiple keys.
Example:
Say you have an ArrayList of String you want to pass from ClassA to ClassB:
ClassA:
for (int i = 0; i < list.size(); i++) {
sharedPref.edit().putString("text" + i, "abcde").apply();
}
ClassB:
for (int i = 0; i < list.size(); i++) {
sharedPref.getString("text" + i, null);
}
If you have problems with the listsize, you can also pass the listsize to sharedpref and retrieve it again.

Why null value in my HashMap?

Why is phonenumber in my HashMap giving me a null value? The idea is that I loop through all contacts on my phone. In my try - catch statement, which is working fine, I see all my contacts in logcat with :
System.out.println("JSON: " + phonenumber);
But with my code System.out.println("contact is : " + phonenumber); later on in the Hashmap I get in logcat :
contact is : null
I want to post all the phone numbers to a MySql database, can you tell me what I am doing wrong ?
public class MainActivity extends AppCompatActivity {
// this is the php file we are contacting with Volley
private static final String CHECKPHONENUMBER_URL = "http://www.sitetocheckwithVolley.com/filetocheckwithVolley.php";
//we are posting phoneNo, which in PHP is phonenumber
public static final String KEY_PHONENUMBER = "phonenumber";
//alContacts is a list of all the phone numbers
public static final ArrayList<String> alContacts = new ArrayList<String>();
Button buttonCheck;
TextView textView;
String phonenumber;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonCheck = (Button) findViewById(R.id.buttonCheck);
textView = (TextView) findViewById(R.id.textView);
//get the names and phone numbers of all contacts in phone book
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
null, null, null, null);
if (cur.getCount() > 0) {
while (cur.moveToNext()) {
String id = cur.getString(
cur.getColumnIndex(ContactsContract.Contacts._ID));
if (cur.getInt(cur.getColumnIndex(
ContactsContract.Contacts.HAS_PHONE_NUMBER)) > 0) {
Cursor pCur = cr.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
new String[]{id}, null);
while (pCur.moveToNext()) {
String phoneNo = pCur.getString(pCur.getColumnIndex(
ContactsContract.CommonDataKinds.Phone.NUMBER));
alContacts.add(phoneNo);
// break;
}
pCur.close();
}
}
}
buttonCheck.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
CheckifUserisContact();
}
});
}
private void CheckifUserisContact() {
StringRequest stringRequest = new StringRequest(Request.Method.POST, CHECKPHONENUMBER_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObjectContact = new JSONObject();
//put all phone contacts into jsonObjectContact
for (int i = 0; i < alContacts.size(); i++)
{
// jsonObjectContact will be of the form {"phone_number":"123456789"}
jsonObjectContact.put("phone_number", alContacts.get(i));
//make a new string phonenumber for each JSON contact
phonenumber = jsonObjectContact.getString("phone_number");
textView.append(phonenumber + " \n");
System.out.println("JSON: " + phonenumber);
}
} catch (final JSONException e) {
Log.e("FAILED", "Json parsing error: " + e.getMessage());
} }
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, error.toString(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
//The KEY, KEY_PHONENUMBER = "phonenumber" . In PHP we will have $_POST["phonenumber"]
//The VALUE, phonenumber, will be of the form "12345678"
params.put(KEY_PHONENUMBER,phonenumber);
System.out.println("contact is : " + phonenumber);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
I get in logcat :
contact is : null
Because it's never assigned between onCreate and the getParams() methods
String phonenumber; // null until onResponse
It'll also continue to be null while alContacts.isEmpty() according to the logic of the code
//The VALUE, phonenumber, will be of the form "12345678"
Okay, then set it to that instead of not setting it at all
You seem to be using a String phoneNo... Is that what you want instead? Then don't make a secondary String variable and instead assign the field. However, then you only are posting the last string of the contacts, not the whole list
Note, this is how to correctly iterate a Cursor
if (cur.moveToFirst()) {
while (cur.moveToNext()) {
Or simply
for (cur.moveToFirst(); cur.moveToNext(); ) {
And, as pointed out, you're collecting a list, but only putting in one element into the parameters. Did you want to post a JSONArray?
Thanks to cricket_007 answer above, I modified my code like so :
public class MainActivity extends AppCompatActivity {
// this is the php file we are contacting with Volley
private static final String CHECKPHONENUMBER_URL = "http://www.thesitetocheck.com/thefiletocheck.php";
//we are posting phoneNo, which in PHP is phonenumber
public static final String KEY_PHONENUMBER = "phonenumber";
//alContacts is a list of all the phone numbers
public static final ArrayList<String> alContacts = new ArrayList<String>();
JSONObject jsonObjectContact = new JSONObject();
Button buttonCheck;
TextView textView;
String phoneNo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonCheck = (Button) findViewById(R.id.buttonCheck);
textView = (TextView) findViewById(R.id.textView);
//get the names and phone numbers of all contacts in phone book
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
null, null, null, null);
if (cur.moveToFirst()) {
while (cur.moveToNext()) {
String id = cur.getString(
cur.getColumnIndex(ContactsContract.Contacts._ID));
if (cur.getInt(cur.getColumnIndex(
ContactsContract.Contacts.HAS_PHONE_NUMBER)) > 0) {
Cursor pCur = cr.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
new String[]{id}, null);
while (pCur.moveToNext()) {
phoneNo = pCur.getString(pCur.getColumnIndex(
ContactsContract.CommonDataKinds.Phone.NUMBER));
alContacts.add(phoneNo);
// break;
}
pCur.close();
}
}
}
buttonCheck.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
try {
//put all phone contacts into jsonObjectContact
for (int i = 0; i < alContacts.size(); i++)
{
// jsonObjectContact will be of the form {"phone_number":"123456789"}
jsonObjectContact.put("phone_number", alContacts.get(i));
textView.append(jsonObjectContact + " \n");
System.out.println("JSON: " + jsonObjectContact);
}
} catch (final JSONException e) {
Log.e("FAILED", "Json parsing error: " + e.getMessage());
}
CheckifUserisContact();
}
});
}
private void CheckifUserisContact() {
StringRequest stringRequest = new StringRequest(Request.Method.POST, CHECKPHONENUMBER_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, error.toString(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
//The KEY, KEY_PHONENUMBER = "phonenumber" . In PHP we will have $_POST["phonenumber"]
//The VALUE, phonenumber, will be of the form "12345678"
params.put(KEY_PHONENUMBER,jsonObjectContact.toString());
System.out.println("contact is : " + jsonObjectContact);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
}

Getting an array from a JSON object in Java

How would I go about parsing this JSON object and getting the "groups" array in Java on Android.
{ "groups": [ "Total_Social_Beta_Testers", "Test_Group" ] }
Here's my code:
LoginActivity.java
Response.Listener<String> responseListener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
boolean success = jsonResponse.getBoolean("success");
if (success) {
String username = jsonResponse.getString("username");
String email = jsonResponse.getString("email");
String gender = jsonResponse.getString("gender");
String country = jsonResponse.getString("country");
String verified = jsonResponse.getString("verified");
String avatar = jsonResponse.getString("avatar");
//String group = jsonResponse.getString("groups");
int numlength = 0;
int CI = 0;
JSONArray jsonArrayGR = jsonResponse.getJSONArray("groups");
//String array of 500 spots
String rows = "";
for (int i = 0; i < jsonArrayGR.length(); i++){
CI++;
rows = jsonArrayGR.getString(i);
}
//int rows = jsonResponse.getInt("rows");
//Starting Activity
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
intent. addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("username", username);
intent.putExtra("email", email);
intent.putExtra("gender", gender);
intent.putExtra("country", country);
intent.putExtra("verified", verified);
intent.putExtra("avatar", avatar);
intent.putExtra("groups", rows);
//intent.putExtra("rows", rows);
session.createUserSession(
username,
email,
gender,
country,
verified,
avatar,
rows
);
Toast.makeText(getBaseContext(), "Login succeed, welcome!" , Toast.LENGTH_LONG).show();
//Adding a new flag to start the activity
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
LoginActivity.this.startActivity(intent);
_loginButton.setEnabled(true);
finish();
} else {
onLoginFailed();
}
}
catch (JSONException e){
e.printStackTrace();
}
}
};
LoginRequest loginRequest = new LoginRequest(e, password, responseListener);
RequestQueue queue = Volley.newRequestQueue(LoginActivity.this);
queue.add(loginRequest);
UserSession.java
public void createUserSession(
String name,
String email,
String gender,
String country,
String verified,
String avatar,
String groups){
//Storage_Start session
editor.putBoolean(IS_USER_LOGIN, true);
// Storing name in pref
editor.putString(KEY_NAME, name);
//Storage of the email in pref
editor.putString(KEY_EMAIL, email);
//Storing the gender
editor.putString(KEY_GENDER, gender);
//Storing the country
editor.putString(KEY_COUNTRY, country);
//Storing the verified
editor.putString(KEY_VERIFIED, verified);
//Storing avatar
editor.putString(KEY_AVATAR, avatar);
//Storing groups
editor.putString(KEY_GROUPS, groups);
//Storing the gRows
//editor.putInt(INT_GROUPS, numlength);
//commit changes
editor.commit();
}
/**
* Get stored session data
* */
public HashMap<String, String> getUserDetails(){
//Use hashmap to store user credentials
HashMap<String, String> user = new HashMap<String, String>();
// user name
user.put(KEY_NAME, pref.getString(KEY_NAME, null));
// user email id
user.put(KEY_EMAIL, pref.getString(KEY_EMAIL, null));
//gender
user.put(KEY_GENDER, pref.getString(KEY_GENDER, null));
//country
user.put(KEY_COUNTRY, pref.getString(KEY_COUNTRY, null));
//verifed?
user.put(KEY_VERIFIED, pref.getString(KEY_VERIFIED, null));
//Avatar
user.put(KEY_AVATAR, pref.getString(KEY_AVATAR, null));
//Groups
user.put(KEY_GROUPS, pref.getString(KEY_GROUPS, null));
// return user
return user;
}
UPDATE
This is where I am storing the values into the recyclerview:
public class ChatsAdapter extends RecyclerView.Adapter<ChatsAdapter.MyViewHolder> {
private List<Groups> chatlist;
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView group;
public MyViewHolder(View view) {
super(view);
group = (TextView) view.findViewById(R.id.groups);
}
}
public ChatsAdapter(List<Groups> chatlist){
this.chatlist = chatlist;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.chat_row_list, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
Groups groups = chatlist.get(position);
holder.group.setText(groups.getTitle());
}
#Override
public int getItemCount() {
return chatlist.size();
}
}
And this is how I am defining the strings:
public class Groups {
private String groups = "";
public Groups() {
}
public Groups(String groups) {
this.groups = groups;
}
public String getTitle() {
return groups;
}
}
This is how I am displaying the values set by the adapter (above) in my main activity:
//groups
String g = user.get(UserSessionManager.KEY_GROUPS);
String numrows = user.get(UserSessionManager.INT_GROUPS);
//String grows = user.get(UserSessionManager.INT_GROUPS);
int rows = Integer.parseInt(numrows);
Groups groups = new Groups(g);
groupslist.add(groups);
chatsAdapter.notifyDataSetChanged();
i believe here you must be facing problem
for (int i = 0; i < jsonArrayGR.length(); i++){
CI++;
rows = jsonArrayGR.getString(i);
}
this is because you are not appending rows value in each loop, instead you are over writing the previous values.
easy solution
rows = jsonArrayGR.getString(i)+rows;
best solution
StringBuilder rows = new StringBuilder();
for (int i = 0; i < jsonArrayGR.length(); i++){
CI++;
rows.append(jsonArrayGR.getString(i));
}
and finally use it in your code
intent.putExtra("groups", rows);
P.S. if you want to use rows as String later, just use String rows = rows.toString();
i hope this will surely help you :D
You should make a ArrayList<String> from this JSONArray and use this List to fill your RecyclerView,
ArrayList<String> listdata = new ArrayList<String>();
if (jArray != null) {
for (int i=0;i<jArray.length();i++)
listdata.add(jsonArrayGR.getString(i));
}
Now you can send this List to your MainActivity and fill your RecyclerView, which is required by you.
In current Activity ->
Bundle extra = new Bundle();
extra.putSerializable("list", listdata);
Intent intent = new Intent(getBaseContext(), MainActivity.class);
intent.putExtra("extra", extra);
In Mainactivity ->
Bundle extra = getIntent().getBundleExtra("extra");
ArrayList<Object> objects = (ArrayList<Object>) extra.getSerializable("objects")
in your app.gradle, add this line under dependencies
compile 'com.google.code.gson:gson:2.3'
and the sync your project.
Now create a .java file with name GroupsModal.java
add this in your GroupsModal.java file
private Groups groups;
//getters and setters
Now create a .java file with name Groups.java and add these lines :
private String Total_Social_Beta_Testers;
//getters and setters
now in your loginActivity.java
#Override
public void onResponse(String response) {
GroupsModal groupsModal = gson.fromJson(response, GroupsModal.class);
if(groupsModal.getSuccessResponse == 200){
// successfully logged in
/*
* you can create classes and variables according to your JSON here
* for gson.fromJson,
* define at the top of loginActivity,
* private Gson gson = new Gson();
*/
}
}
Hope it helps..
String[] getStringArray(String name, JSONObject object) throws JSONException {
JSONArray jsonArray = object.getJSONArray(name);
String[] array = new String[jsonArray.length()];
for (int i = 0; i < jsonArray.length(); i++){
array[i] = jsonArray.getString(i);
}
return array;
}

Categories

Resources