Why null value in my HashMap? - java

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);
}
}

Related

How strart method execution after one method finished executing

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

How do I get current user's input data to show in listview?

I have an app where I use the info provided by the user to get a list of data
Using the code below, I'm getting two different results:
When where username = '$username' is presented on the PHP side, I receive just the Toast message. However, ListView remains empty.
When I remove where username = '$username' from PHP side, Toast message is displayed and the ListView also shows some content
Could you please help me to undestand why the ListView remains empty on that specific case?
Thanks in advance
Java
public void current_user() {
String url = "http://websie/my.php";
Calendar calendar = Calendar.getInstance();
SimpleDateFormat dayes = new SimpleDateFormat("dd-MM-yyyy");
final String created_date = dayes.format(calendar.getTime());
StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//System.out.println(response);
// Toast.makeText(MainActivity.this,response,Toast.LENGTH_SHORT).show();
Toast.makeText(show_post_all_sales_2x100.this, response.toString(), Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.INVISIBLE);
listViewAdapter = new ListViewAdapter(show_post_all_sales_2x100.this, R.layout.listview_items_layout, SubjectList);
listView.setAdapter(listViewAdapter);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(show_post_all_sales_2x100.this, error.toString(), Toast.LENGTH_SHORT).show();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("username", User.getUsername());
params.put("created_date", created_date);
return params;
}
};
RequestQueue requestQueue = com.android.volley.toolbox.Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
private class ParseJSonDataClass extends AsyncTask<Void, Void, Void> {
public Context context;
String FinalJSonResult;
public ParseJSonDataClass(Context context) {
this.context = context;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpParseClass httpParseClass = new HttpParseClass(HttpURL);
try {
httpParseClass.ExecutePostRequest();
if (httpParseClass.getResponseCode() == 200) {
FinalJSonResult = httpParseClass.getResponse();
if (FinalJSonResult != null) {
JSONArray jsonArray = null;
try {
jsonArray = new JSONArray(FinalJSonResult);
JSONObject jsonObject;
Subjects subjects;
SubjectList = new ArrayList<Subjects>();
for (int i = 0; i < jsonArray.length(); i++) {
jsonObject = jsonArray.getJSONObject(i);
String tempName = jsonObject.getString("username").toString();
String tempFullForm = jsonObject.getString("created_date").toString();
subjects = new Subjects(tempName, tempFullForm);
SubjectList.add(subjects);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} else {
Toast.makeText(context, httpParseClass.getErrorMessage(), Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
progressBar.setVisibility(View.INVISIBLE);
listViewAdapter = new ListViewAdapter(show_post_all_sales_2x100.this, R.layout.listview_items_layout, SubjectList);
listView.setAdapter(listViewAdapter);
}
}
PHP
<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
include 'DatabaseConfig.php';
$username = $_POST['username'];
// Create connection
$conn = new mysqli($HostName, $HostUser, $HostPass, $DatabaseName);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM post_2x where username = '$username'" ;
$result = $conn->query($sql);
if ($result->num_rows >0) {
while($row[] = $result->fetch_assoc()) {
$tem = $row;
$json = json_encode($tem);
}
} else {
echo "No Results Found.";
}
echo $json;
$conn->close();
}
?>
Result when where username = '$username' is present
Result when I remove where username = '$username'

Empty ArrayList Inside onResponse

I am developing an app for Downloading Images and their Description from Flickr.
I am setting Description String into GetterAndSetter Class's ArrayList and when i want to fetch the Data from that class,
even logger not Printing. And so that when i tried to set the values from stringArray onto the UI, I am getting ArrayIndexoutofBound Exception.
My Code is Following :
#Override
protected void onCreate(Bundle savedInstanceState) {
...
LoadImages(this);
...
}
My LoadImages Method :
private void LoadImages(MainActivity mainActivity) {
if (checkInternet()) {
StringRequest stringRequest = new StringRequest(URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("Respone", "onResponse: " + response);
// Used to Get List of Images URLs
getResponse = ParseJSON(response);
List<String> urlList = getResponse.get(0);
List<String> titles = getResponse.get(1);
// Getting String Array from GetterAndSetter Class...
// Not Properly Getting from there...
List<String> Details = getterAndSetter.getStringList();
// Printing Check
for (String urls:urlList) {
Log.d("urls", urls);
}
// Printing Check
for (String title:titles) {
Log.d("titles", title);
}
// Problem is here, Not Getting
**This is not even Executing...**
for (String str: Details) {
Log.d("GetDetails", str);
}
...
}
}, error -> {
Log.d(TAG, "onErrorResponse: Error Occured...");
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
mView.show(getSupportFragmentManager(), "Loading...");
} else {
Toast.makeText(this, "Turn Internet on...", Toast.LENGTH_SHORT).show();
}
}
My ParseJSON method :
ArrayList<ArrayList<String>> ParseJSON(String URL) {
try {
...
ArrayList<String> listURLS = new ArrayList<>();
ArrayList<String> Titles = new ArrayList<>();
ArrayList<ArrayList<String>> result = new ArrayList<>();
for (int i = 0; i < photo.length(); i++) {
JSONObject photosJSONObject = photo.getJSONObject(i);
String FarmID = photosJSONObject.getString("farm");
String ServerID = photosJSONObject.getString("server");
String ID = photosJSONObject.getString("id");
String SecretID = photosJSONObject.getString("secret");
String ImageTitle = photosJSONObject.getString("title");
listURLS.add(i, CreatePhotoURL(FarmID, ServerID, ID, SecretID));
Titles.add(i, ImageTitle);
String CreateURL = "https://api.flickr.com/services/rest/?method=flickr.photos.getInfo&api_key=" + API_Key + "&photo_id=" + ID + "&format=json&nojsoncallback=1";
AddtoList(CreateURL);
result.add(listURLS);
result.add(Titles);
}
return result;
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
My AddtoList Method :
public void AddtoList(String CreateURL) {
RequestQueue requestQueue = Volley.newRequestQueue(this);
StringRequest stringRequest = new StringRequest(CreateURL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("Desc", response);
JSONObject root = null;
try {
root = new JSONObject(response);
JSONObject photo = root.getJSONObject("photo");
String username = photo.getJSONObject("owner").getString("username");
String DateTaken = photo.getJSONObject("dates").getString("taken");
String Views = photo.getString("views");
String FormattedStr = "Date Taken : " + DateTaken + "\n" + "Views : " + Views + "\n" + "User Name : " + username + "\n";
// Properly Working...
Log.d("Describe", FormattedStr);
// I cant say about this...
getterAndSetter.getStringList().add(FormattedStr);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, "onErrorResponse: " + error.toString());
}
});
requestQueue.add(stringRequest);
}
My GetterAndSetter Class :
public final class GetterAndSetter {
private final ArrayList<String> stringList = new ArrayList<>();
public ArrayList<String> getStringList() {
return stringList;
}}

My Simple Adapter Wont Populate my listview

I am creating an android application and my code will loop through the json data and if finds a match to the string that i have placed in ( in this case "Guil Hernandez") , then it will add that name to an array list of hashmaps. I then populate my listview with a simple adapter. Everything is working properly, but my listview will not appear. Am i doing this sorting "algorithm" wrong? Also if you know of a better way to do the sorting to find a match..PLEASE LET ME KNOW. i am still new to this. Thank you in advance!
private void handleResponse() {
if (mNameDataJson == null ) {
// TODO: handle error
} else {
try {
JSONArray namesArray = mNameDataJson.getJSONArray("posts");
ArrayList<HashMap<String , String> > nameArrayList = new ArrayList<HashMap<String, String>>();
for ( int i = 0 ; i < namesArray.length() ; i++ ) {
JSONObject unit = namesArray.getJSONObject(i);
String name = unit.getString(KEY_NAME);
name = Html.fromHtml(name).toString();
String title = unit.getString(KEY_TITLE);
title = Html.fromHtml(title).toString();
HashMap<String , String> hashMap = new HashMap<String, String>();
if (name == "Guil Hernandez") {
hashMap.put(KEY_NAME, name);
hashMap.put(KEY_TITLE, title);
nameArrayList.add(hashMap);
} else {
Log.v(TAG , "no match");
}
}
String[] keys = { KEY_NAME , KEY_TITLE };
int[] ids = {android.R.id.text1 , android.R.id.text2};
SimpleAdapter adapter = new SimpleAdapter(MyActivity.this , nameArrayList , android.R.layout.simple_list_item_2,
keys , ids);
setListAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
full code here :
public class MyActivity extends ListActivity {
private JSONObject mNameDataJson;
private final String TAG = MyActivity.class.getSimpleName();
private final String KEY_NAME = "author";
private final String KEY_TITLE = "title";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
GetNameData getNameData = new GetNameData();
getNameData.execute();
}
private void handleResponse() {
if (mNameDataJson == null ) {
// TODO: handle error
} else {
try {
JSONArray namesArray = mNameDataJson.getJSONArray("posts");
ArrayList<HashMap<String , String> > nameArrayList = new ArrayList<HashMap<String, String>>();
for ( int i = 0 ; i < namesArray.length() ; i++ ) {
JSONObject unit = namesArray.getJSONObject(i);
String name = unit.getString(KEY_NAME);
name = Html.fromHtml(name).toString();
String title = unit.getString(KEY_TITLE);
title = Html.fromHtml(title).toString();
HashMap<String , String> hashMap = new HashMap<String, String>();
if (name == "Guil Hernandez") {
hashMap.put(KEY_NAME, name);
hashMap.put(KEY_TITLE, title);
nameArrayList.add(hashMap);
} else {
Log.v(TAG , "no match");
}
}
String[] keys = { KEY_NAME , KEY_TITLE };
int[] ids = {android.R.id.text1 , android.R.id.text2};
SimpleAdapter adapter = new SimpleAdapter(MyActivity.this , nameArrayList , android.R.layout.simple_list_item_2,
keys , ids);
setListAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
private class GetNameData extends AsyncTask<Object, Void, JSONObject> {
JSONObject jsonResponse = null;
#Override
protected JSONObject doInBackground(Object... objects) {
String nameUrl = "http://blog.teamtreehouse.com/api/get_recent_summary/?count=20";
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(nameUrl)
.build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
#Override
public void onFailure(Request request, IOException e) {
}
#Override
public void onResponse(Response response) throws IOException {
String responseString = response.body().string();
Log.v(TAG , responseString);
try {
jsonResponse = new JSONObject(responseString);
} catch (JSONException e) {
e.printStackTrace();
}
}
});
return jsonResponse;
}
#Override
protected void onPostExecute(JSONObject jsonObject) {
mNameDataJson = jsonObject;
handleResponse();
}
}
}
If you want to compare strings use equals(). Like this:
if (name.equals("Guil Hernandez")) {
hashMap.put(KEY_NAME, name);
hashMap.put(KEY_TITLE, title);
nameArrayList.add(hashMap);
}

How to update the database,while changing in our server side

I am sending my Server side JSON data into database,after that i am display in an listview. But while changing in an server side or my json data will increase, it will not reflect or change in my db,Actually after changing my JSON, i want my db also update like Old+new. It has to save the new one also in db while any data add in server side also.
This my JSON part:
{
"post": [
{
"id": 249,
"title": "Career",
"content": "Last ten days ,work is not going well",
"count": 0
},
{
"id": 248,
"title": "Career",
"content": "Last ten days ,work is not going well",
"count": 0
},
]
}
This JSON value has to store in db,if next time in website some thing will add,my json will also increase,My db also wants to add that data,Rightnow is not adding that data,only one time its fetching and displaying.
This is my Mainactivity.java
#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.getCount()>0)
{
fillData(projectsCursor);
Log.i("filling", "...");
}
else
{
new GetDataAsyncTask().execute();
}
btnGetSelected = (Button) findViewById(R.id.btnget);
btnGetSelected.setOnClickListener(this);
}
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();
mDbHelper=new GinfyDbAdapter(MainActivity.this); // initialize mDbHelper before.
mDbHelper.open();
Cursor projectsCursor = mDbHelper.fetchAllProjects();
if(projectsCursor.getCount()>0)
{
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("http://192.168.1.18:3001/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");
}
}
Here i mention my dpclass also.
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;
}
public boolean updateProject(long _id, String title, String content, String count) {
ContentValues args = new ContentValues();
args.put(CATEGORY_COLUMN_TITLE, title );
args.put(CATEGORY_COLUMN_CONTENT, content );
args.put(CATEGORY_COLUMN_COUNT, count );
return mDb.update(DATABASE_TABLE_PROJ, args, CATEGORY_COLUMN_ID + "=" + _id, null) > 0;
}
}
My problem is:For first time it fetches my JSON data and save in db,next time while launching its not getting newly added part of json data,I want that old and new JSON data should be store in db.
please use insert or replase raw query instead this look this.
SQLite "INSERT OR REPLACE INTO" vs. "UPDATE ... WHERE"
String query = INSERT OR REPLACE INTO DATABASE_TABLE_PROJ
(CATEGORY_COLUMN_ID,CATEGORY_COLUMN_TITLE,CATEGORY_COLUMN_CONTENT,CATEGORY_COLUMN_COUNT)
VALUES
('1', 'Muhammad','xyz','2');
db.execSQL(query);
public class Mainactivity extends Activity{
ArrayList<String> ID = new ArrayList<String>();
ArrayList<String> TITLE= new ArrayList<String>();
ArrayList<String> CONTENT= new ArrayList<String>();
ArrayList<String> COUNT= new ArrayList<String>();
protected onCreate(Bundle savedInastanceState){
}
public void getData() {
//your json code
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");
ID.add(id);
TITLE.add(title);
CONTENT.add(content);
COUNT.add(count);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
private class GetDataAsyncTask extends AsyncTask<Void, Void, Void> {
private ProgressDialog Dialog = new ProgressDialog(MainActivity.this);
protected void onPreExecute() {
//
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
Dialog.dismiss();
//
}
#Override
protected Void doInBackground(Void... params) {
getData();
return null;
}
#Override
protected void onPostExecute(Void result) {
for(int i=0; i<ID.size(); i++){
mDbHelper=new GinfyDbAdapter(MainActivity.this);
mDbHelper.open();
mDbHelper.saveCategoryRecord(new Category(ID.get(i),TITLE.get(i),CONTENT.get(i),COUNTER.get(i)));
}
}

Categories

Resources