i am creating an android application in which i want to access database from mysql for user name, phone no and email address. and i want to compare phone no from android phone contact list and the phone no getting from mysql database. for that purpose i use 2 arraylist 1st for phone contact and 2nd for mysql phone no.
my main problem is when i compare both the arraylist then i shows no result.
i attach here the code please someone help me to solve this problem.
public class PhoneNoActivity extends Activity{
JSONArray jArray,jArray1;
JSONObject jobj;
String result = null,phone=null;
InputStream is = null;
StringBuilder sb=null;
double lat=0;
double lon=0;
String user=null;
ArrayList<NameValuePair> nameValuePairs;
ListView lv;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
String phno=null;
ArrayList<String> cntPhone=new ArrayList<String>();
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));
String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
if (Integer.parseInt(cur.getString(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));
if(phoneNo.length()>10) {
phno=phoneNo.subSequence(phoneNo.length()-10, phoneNo.length()).toString();
// Log.e(name, phno);
}
cntPhone.add(phoneNo);
}
pCur.close();
}
}
}
ArrayList<String> cntOnline=new ArrayList<String>();
try {
nameValuePairs = new ArrayList<NameValuePair>();
/*String phone=null;
for(int k=0;k<=cntPhone.size();k++) {
Log.e("k",k+"");
phone=cntPhone.get(k);
nameValuePairs.add(new BasicNameValuePair("phone", phone));
*/
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://10.0.2.2/ah_login_api/select.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
String line="0";
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result=sb.toString();
Log.e("result=", result);
jArray = new JSONArray(result);
JSONObject json_data=null;
for(int i=0;i<jArray.length();i++){
json_data = jArray.getJSONObject(i);
user=json_data.getString("user");
phone=json_data.getString("phone");
lat=json_data.getDouble("email");
cntOnline.add(phone);
}
for(String s:cntOnline) {
for(String s1:cntPhone ) {
if(s.equals(s1)) {
Log.e("match found", phone);
}
}
}
/*
for(int l=0;l<cntOnline.size();l++) {
Log.e("loop start", ""+l);
for(int k=0;k<cntPhone.size();k++) {
if(cntPhone.get(k).trim().equals(cntOnline.get(l).trim())) {
Log.e("match found", phone);
}
}
}*/
//}
} catch(Exception ex) {
Log.e("Exception in ",ex.toString());
}
}
}
and this is my php code from which i access details
<?php
mysql_connect("localhost","root","");
mysql_select_db("MyContact");
$sql=mysql_query("select * from newuser");
while($row=mysql_fetch_assoc($sql))
$output[]=$row;
print(json_encode($output));
mysql_close();
?>
/* Retrieves phone numbers from Phone Contact List */
public ArrayList<String> getNumber() {
String phoneNumber;
ArrayList<String> contact_number = new ArrayList<String>();
ContentResolver cr = getApplicationContext().getContentResolver();
Cursor phones = cr.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null,
null, null);
while (phones.moveToNext()) {
phoneNumber = phones
.getString(phones
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
System.out.println(".................." + phoneNumber);
contact_number.add(phoneNumber);
}
phones.close();
return contact_number;
}
/* Gets the Numbers from MySQL database using object "Contact" and Compares it with the method "getNumber()" which retrieves phone numbers from Phone Contact List */
#SuppressWarnings("unused")
private Contact convertContact(JSONObject obj) throws JSONException {
Contact contact = new Contact();
String name = obj.getString("user_name");
String mobile_no = obj.getString("mobile_no");
boolean isMatched = false;
contact_number = getNumber();
for (int i = 0; i < contact_number.size(); i++) {
if (mobile_no.equals(contact_number.get(i))) {
isMatched = true;
contact.setName(name);
contact.setMobileNo(mobile_no);
}
}
return isMatched ? contact : null;
}
/* If the number from database matches with the phone contact list add and generate in listview */
private class AsyncTasak extends
AsyncTask<String, Void, ArrayList<Contact>> {
#Override
protected void onPostExecute(ArrayList<Contact> result) {
super.onPostExecute(result);
arrayadapter.setItemList(result);
arrayadapter.notifyDataSetChanged();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected ArrayList<Contact> doInBackground(String... params) {
ArrayList<Contact> result = new ArrayList<Contact>();
try {
URL u = new URL(params[0]);
HttpURLConnection conn = (HttpURLConnection) u.openConnection();
conn.setRequestMethod("GET");
conn.connect();
InputStream is = conn.getInputStream();
byte[] b = new byte[1024];
ByteArrayOutputStream baos = new ByteArrayOutputStream();
while (is.read(b) != -1)
baos.write(b);
String JSONResp = new String(baos.toByteArray());
JSONArray arr = new JSONArray(JSONResp);
for (int i = 0; i < arr.length(); i++) {
Contact temp = convertContact(arr.getJSONObject(i));
if (temp != null) {
result.add(temp);
}
}
return result;
} catch (Throwable t) {
t.printStackTrace();
}
return null;
}
Related
i call MyTask().execute(); in onCreate() of MainAcivity Class in my application. it Busy or Hang my application for long time. please help me why? i want my work in background so that it can't disturb my app. Why my app become busy and unresponsive?
Class code is below:
private class MyTask extends AsyncTask<String, Integer, String> {
// Runs in UI before background thread is called
#Override
protected void onPreExecute() {
super.onPreExecute();
// Do something like display a progress bar
}
// This is run in a background thread
#Override
protected String doInBackground(String... params) {
checkUser();
return "";
}
// This is called from background thread but runs in UI
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
// Do things like update the progress bar
}
// This runs in UI when background thread finishes
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
// Do things like hide the progress bar or change a TextView
}
}
checkUser() method code is below
private void checkUser(){
// now here we convert this list array into json string
final String server_url="http://www.xxxx.com/TruCaller/check_user.php"; // url of server check this 100 times it must be working
// volley
StringRequest stringRequest=new StringRequest(Request.Method.POST, server_url,
new Response.Listener<String>() {
#Override
public void onResponse(String response)
{
final String result=response.toString().trim();
if(result.equals("not found")){
//Toast.makeText(MainActivity.this,"Wait...",Toast.LENGTH_LONG).show();
// Log.d("responsedd", "result not found fffffffff: "+result);
getContacts2();
}else{
}
// Log.d("responsedd", "result : "+result); //when response come i will log it
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error)
{
error.printStackTrace();
error.getMessage(); // when error come i will log it
}
}
)
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("identifier", UIDD);
Log.d("responsedd", "result not found ggggggggggg: "+ UIDD);
return params;
}
};
Vconnection.getnInstance(this).addRequestQue(stringRequest); // vConnection i claas which used to connect volley
}
getContacts2() method code is below:
public void getContacts2() {
if (!mayRequestContacts()) {
return;
}
// contactList = new ArrayList<String>();
String phoneNumber = null;
String email = null;
Uri CONTENT_URI = ContactsContract.Contacts.CONTENT_URI;
String _ID = ContactsContract.Contacts._ID;
String DISPLAY_NAME = ContactsContract.Contacts.DISPLAY_NAME;
String HAS_PHONE_NUMBER = ContactsContract.Contacts.HAS_PHONE_NUMBER;
Uri PhoneCONTENT_URI = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
String Phone_CONTACT_ID = ContactsContract.CommonDataKinds.Phone.CONTACT_ID;
String NUMBER = ContactsContract.CommonDataKinds.Phone.NUMBER;
Uri EmailCONTENT_URI = ContactsContract.CommonDataKinds.Email.CONTENT_URI;
String EmailCONTACT_ID = ContactsContract.CommonDataKinds.Email.CONTACT_ID;
String DATA = ContactsContract.CommonDataKinds.Email.DATA;
StringBuffer output;
ContentResolver contentResolver = getContentResolver();
cursor = contentResolver.query(CONTENT_URI, null, null, null, null);
// Iterate every contact in the phone
if (cursor.getCount() > 0) {
counter = 0;
while (cursor.moveToNext()) {
output = new StringBuffer();
String contact_id = cursor.getString(cursor.getColumnIndex(_ID));
String name = cursor.getString(cursor.getColumnIndex(DISPLAY_NAME));
String phoneC = "", adressC = "", emailC = "",country_code="";
int hasPhoneNumber = Integer.parseInt(cursor.getString(cursor.getColumnIndex(HAS_PHONE_NUMBER)));
Bitmap bitmap = null;
String image = "";
if (hasPhoneNumber > 0) {
////////////////////Phone numbers with this name..... 2 Testing ....////////////////
String phoneNumber2 = "";
final String[] projection = new String[]{ContactsContract.CommonDataKinds.Phone.NUMBER, ContactsContract.CommonDataKinds.Phone.TYPE,};
final Cursor phone = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, projection, ContactsContract.Data.CONTACT_ID + "=?", new String[]{String.valueOf(contact_id)}, null);
if (phone.moveToFirst()) {
final int contactNumberColumnIndex = phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DATA);
phoneC = "";
while (!phone.isAfterLast()) {
////////////////////////////////////////////
String x = phone.getString(contactNumberColumnIndex);
bitmap = retrieveContactPhoto(MainActivity.this, x);
String countryCode = countryCode(phone.getString(contactNumberColumnIndex));
country_code = countryCode;
// String swissNumberStr = "03348633664";
PhoneNumberUtil phoneUtil = PhoneNumberUtil.createInstance(getApplicationContext());
Phonenumber.PhoneNumber pNumberProto;
String phoneVerfid="";
try {
pNumberProto = phoneUtil.parse(phone.getString(contactNumberColumnIndex), countryCode);
// System.err.println("NumberParseException was thrown:>>>>>>>>>>>> " + pNumberProto);
boolean isValid = phoneUtil.isValidNumber(pNumberProto);
if(isValid){
System.out.println(phoneUtil.format(pNumberProto, PhoneNumberUtil.PhoneNumberFormat.INTERNATIONAL));
phoneVerfid = phoneUtil.format(pNumberProto, PhoneNumberUtil.PhoneNumberFormat.E164);
}
} catch (NumberParseException e) {
// System.err.println("NumberParseException was thrown: " + e.toString() +" ???" +phone.getString(contactNumberColumnIndex) + countryCode);
}
///////////////////////////////
phoneNumber2 = phoneVerfid + "_";
// output.append("\n Phone number:" + phoneNumber2);
phoneC = phoneC + phoneNumber2;
// System.out.println("Country = "+countryCode(phoneNumber2) + " p= " +phoneNumber2);
phone.moveToNext();
}
}
phone.close();
/////////////////////////////////////////////////////////////
// Read every email id associated with the contact
Cursor emailCursor = contentResolver.query(EmailCONTENT_URI, null, EmailCONTACT_ID + " = ?", new String[]{contact_id}, null);
emailC = "";
email = "";
while (emailCursor.moveToNext()) {
email = emailCursor.getString(emailCursor.getColumnIndex(DATA)) + "%";
if (!emailC.contains(email)) {
emailC = emailC + email;
// output.append("\n Email:" + email);
}
}
emailCursor.close();
//////////// Adresss//////
String postalData = "";
String addrWhere = ContactsContract.Data.CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?";
String[] addrWhereParams = new String[]{String.valueOf(contact_id), ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE};
Cursor addrCur = getContentResolver().query(ContactsContract.Data.CONTENT_URI, null, addrWhere, addrWhereParams, null);
if (addrCur.moveToFirst()) {
postalData = addrCur.getString(addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.FORMATTED_ADDRESS));
//output.append("\n Address:" + postalData);
adressC = adressC + " " + postalData;
}
addrCur.close();
}
if (phoneC != "") {
if (bitmap != null) {
Bitmap bitmap1 = getResizedBitmap(bitmap,210);
image = getStringImage(bitmap1);
if(bitmap1!=null) {
bitmap1.recycle();
}
// System.out.println("KKKKKKKKKKKKKKKKKKK >>>>>>>>> "+image);
}
Contact_Details dt = new Contact_Details(name, phoneC, UIDD, country_code, image, emailC, adressC);
dataArray.add(dt);
if(bitmap!=null){ bitmap.recycle();}
image = "";
}
}
submit1User2Contacs();
}
}
MainAcivity onCreate Method :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
new MyTask().execute();}
Looks like you haven't called close method for cursor object.
Calling cursor.close() will solve your problem
i try below code instead of new MyTask().execute() class. and the below code work for me. i also try below code with xxx.run(); method instead of start();. run() method also not work. only thread with xxx.start(); worked. so the correct code is below one. Thanks every one.
new Thread(new Runnable(){
#Override
public void run() {
//my method
checkUser();
}
}).start();
My ListView is not showing anything.
I'm downloading the top stories API from Hacker-News and putting them in my app. I want to put the titles of those stories in my list view (they are over 100).
I download them and store them in a database for permanent storage and then add them to my list view, but NOTHING is showing up in my app. Can anyone explain to me why?
UPDATE: I get a CursorIndexOutOfBoundException problem. ( index 350 out of 350)
public class MainActivity extends AppCompatActivity {
ListView listView;
private SQLiteDatabase myDatabase;
private Cursor cursor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.listView);
DownloadIDs ids = new DownloadIDs();
String URL = "https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty";
ids.execute(URL);
try {
ArrayList<String> titles = new ArrayList<String>();
ArrayAdapter arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, titles);
listView.setAdapter(arrayAdapter);
myDatabase = this.openOrCreateDatabase("HackerNews", MODE_PRIVATE, null);
Cursor cursor1 = myDatabase.rawQuery("SELECT * FROM ids", null);
int index = cursor1.getColumnIndex("urlID");
cursor1.moveToFirst();
while (cursor1 != null) {
String newUrl = "https://hacker-news.firebaseio.com/v0/item/" + cursor1.getString(index) + ".json?print=pretty";
new DownloadContent().execute(newUrl);
cursor1.moveToNext();
}
Cursor cursor2 = myDatabase.rawQuery("SELECT * FROM content", null);
int titleIndex = cursor2.getColumnIndex("title");
cursor2.moveToFirst();
titles.add("Hello");
while(cursor2 != null){
titles.add(cursor2.getString(titleIndex));
arrayAdapter.notifyDataSetChanged();
cursor2.moveToNext();
}
}catch (Exception e){
e.printStackTrace();
}
}
public class DownloadIDs extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
String result = "";
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL(params[0]);
urlConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = urlConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(inputStream);
int data = reader.read();
while (data >= 0) {
char current = (char) data;
result += current;
data = reader.read();
}
return result;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
try {
myDatabase.execSQL("CREATE TABLE IF NOT EXISTS ids (id INTEGER PRIMARY KEY, urlID VARCHAR)");
cursor = myDatabase.rawQuery("SELECT COUNT(*) FROM ids", null);
cursor.moveToFirst();
int count = cursor.getInt(0);
if (!(count > 0)) {
JSONArray ids = new JSONArray(s);
for (int i = 0; i < ids.length(); i++) {
myDatabase.execSQL("INSERT INTO ids (urlID) VALUES ('" + ids.getString(i) + "')");
}
}
}catch (Exception e){
e.printStackTrace();
}
}
}
public class DownloadContent extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
String result = "";
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL(params[0]);
urlConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = urlConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(inputStream);
int data = reader.read();
while (data >= 0) {
char current = (char) data;
result += current;
data = reader.read();
}
return result;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
try {
myDatabase.execSQL("CREATE TABLE IF NOT EXISTS content(id INTEGER PRIMARY KEY, title VARCHAR, url VARCHAR)");
cursor = myDatabase.rawQuery("SELECT COUNT(*) FROM content", null);
cursor.moveToFirst();
int count = cursor.getInt(0);
if (!(count > 0)) {
JSONObject jsonObject = new JSONObject(s);
String title = jsonObject.getString("title");
Log.i("title", title);
String url = jsonObject.getString("url");
Log.i("url", url);
myDatabase.execSQL("INSERT INTO content (title, url) VALUES('" + title + "','" + url + "')");
}
}catch(Exception e){
e.printStackTrace();
}
}
}
}
Got it! I fixed it. I just had to reduce the amount of news (I decided to choose the top 20 ones), and I decided to run only one ASyncTask on my app.
Here is the edited code:
PD: Thanks to #cafebabe1991 as he gave me tips on how to fix it. Thanks!
public class MainActivity extends AppCompatActivity {
ListView listView;
private SQLiteDatabase myDatabase;
ArrayList<String> titles;
ArrayList<String> urls;
ArrayAdapter arrayAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.listView);
titles = new ArrayList<>();
urls = new ArrayList<>();
arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, titles);
listView.setAdapter(arrayAdapter);
try {
myDatabase = this.openOrCreateDatabase("HackerNews", MODE_PRIVATE, null);
DownloadTask downloadTask = new DownloadTask();
String URL = "https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty";
downloadTask.execute(URL);
Cursor cursor = myDatabase.rawQuery("SELECT * FROM content", null);
int titleIndex = cursor.getColumnIndex("title");
int urlIndex = cursor.getColumnIndex("url");
cursor.moveToFirst();
while(cursor!=null){
titles.add(cursor.getString(titleIndex));
urls.add(cursor.getString(urlIndex));
cursor.moveToNext();
}
arrayAdapter.notifyDataSetChanged();
} catch (Exception e) {
e.printStackTrace();
}
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(getApplicationContext(), MainActivity2.class);
MainActivity2.url = urls.get(position);
startActivity(intent);
}
});
}
public class DownloadTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
String articleInfo = "";
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL(params[0]);
urlConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = urlConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(inputStream);
int data = reader.read();
while (data >= 0) {
char current = (char) data;
articleInfo += current;
data = reader.read();
}
//myDatabase.execSQL("CREATE TABLE IF NOT EXISTS ids (id INTEGER PRIMARY KEY, urlID VARCHAR)");
myDatabase.execSQL("CREATE TABLE IF NOT EXISTS content (id INTEGER PRIMARY KEY, title VARCHAR, url VARCHAR)");
myDatabase.delete("content", null, null);
JSONArray ids = new JSONArray(articleInfo);
for (int i = 0; i < 20; i++) {
//myDatabase.execSQL("INSERT INTO ids (urlID) VALUES ('" + ids.getString(i) + "')");
String articleInfo2 = "";
URL url2 = new URL("https://hacker-news.firebaseio.com/v0/item/" + ids.getString(i) + ".json?print=pretty");
HttpURLConnection urlConnection2 = (HttpURLConnection) url2.openConnection();
InputStream inputStream2 = urlConnection2.getInputStream();
InputStreamReader reader2 = new InputStreamReader(inputStream2);
int data2 = reader2.read();
while (data2 >= 0) {
char current2 = (char) data2;
articleInfo2 += current2;
data2 = reader2.read();
}
JSONObject jsonObject = new JSONObject(articleInfo2);
String title = "'" + jsonObject.getString("title").replaceAll("'", "") + "'";
String articleURL = "'" + jsonObject.getString("url") + "'";
myDatabase.execSQL("INSERT INTO content (title, url) VALUES (" + title + "," + articleURL + ")");
}
return null;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
}
}
}
The problem lies in this code
1.)
Cursor cursor1 = myDatabase.rawQuery("SELECT * FROM ids", null);
int index = cursor1.getColumnIndex("urlID");
cursor1.moveToFirst();
while (cursor1 != null) {
String newUrl = "https://hacker-news.firebaseio.com/v0/item/" + cursor1.getString(index) + ".json?print=pretty";
new DownloadContent().execute(newUrl);
cursor1.moveToNext();
}
How ?
You say to to cursor to get you the column index and from that you fetch the item id, but when database is empty the value will be null. Hence the api will not return a response. Additionally you do the same mistake with the cursor as mentioned in the point below.
2.)
int titleIndex = cursor2.getColumnIndex("title");
cursor2.moveToFirst();
titles.add("Hello");
while(cursor2 != null){
titles.add(cursor2.getString(titleIndex));
arrayAdapter.notifyDataSetChanged();
cursor2.moveToNext();
}
How ?
You said to the cursor to move to the first record (moveToFirst()) , what if the currently no record exist. This method returns false if the cursor is empty. So make sure that this method returns true and then proceed.
OR
Do this(Better approach)...
while(cursor.moveToNext()) {
//If inside , that means you are on the next record.Fetch the column values here
}
References :
Cursor methods
Discussion about best ways to iterate a cursor
For loading data into the listview from the database
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
Can anyone help me in fixing my code?
Apparently the problem is that I can't run more than one ASyncTask on my main thread. Can anyone give me some advise as to how I can fix my code?
Thank you!
I apologize for not commenting my code. I can explain if you guys get confused while reading it.
public class MainActivity extends AppCompatActivity {
ListView listView;
private SQLiteDatabase myDatabase;
private Cursor cursor;
boolean finished = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.listView);
myDatabase = this.openOrCreateDatabase("HackerNews", MODE_PRIVATE, null);
Cursor cursor = myDatabase.rawQuery("SELECT * FROM ids", null);
int index = cursor.getColumnIndex("urlID");
cursor.moveToFirst();
DownloadContent content = new DownloadContent();
while(cursor != null){
String newUrl = "https://hacker-news.firebaseio.com/v0/item/" + cursor.getString(index) + ".json?print=pretty";
content.execute(newUrl);
cursor.moveToNext();
}
}
public class DownloadIDs extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
String result = "";
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL(params[0]);
urlConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = urlConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(inputStream);
int data = reader.read();
while (data >= 0) {
char current = (char) data;
result += current;
data = reader.read();
}
return result;
} catch (Exception e) {
e.printStackTrace();
return "Fail";
}
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
myDatabase.execSQL("CREATE TABLE IF NOT EXISTS ids (id INTEGER PRIMARY KEY, urlID VARCHAR)");
cursor = myDatabase.rawQuery("SELECT COUNT(*) FROM ids", null);
cursor.moveToFirst();
int count = cursor.getInt(0);
if (!(count > 0)) {
try {
JSONArray ids = new JSONArray(s);
for (int i = 0; i < ids.length(); i++) {
myDatabase.execSQL("INSERT INTO ids (urlID) VALUES ('" + ids.getString(i) + "')");
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.i("message", "TABLE1 IS NOT EMPTY");
}
}
}
public class DownloadContent extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
String result = "";
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL(params[0]);
urlConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = urlConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(inputStream);
int data = reader.read();
while (data >= 0) {
char current = (char) data;
result += current;
data = reader.read();
}
return result;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
myDatabase.execSQL("CREATE TABLE IF NOT EXISTS content(id INTEGER PRIMARY KEY, title VARCHAR, url VARCHAR)");
cursor = myDatabase.rawQuery("SELECT COUNT(*) FROM content", null);
cursor.moveToFirst();
int count = cursor.getInt(0);
if (!(count > 0)) {
try {
JSONObject jsonObject = new JSONObject(s);
String title = jsonObject.getString("title");
String url = jsonObject.getString("url");
myDatabase.execSQL("INSERT INTO content (title, url) VALUES('" + title +"','" + url + "')");
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.i("mess2", "table 2 is NOT EMPTY");
}
}
}
}
Each AsyncTask instance can only be run once. Simplest way to resolve this is to just create a new instance whenever you need to run it.
while(cursor != null) {
String newUrl = "https://hacker-news.firebaseio.com/v0/item/" + cursor.getString(index) + ".json?print=pretty";
new DownloadContent().execute(newUrl);
cursor.moveToNext();
}
I am storing data into SQLiteDatabase which is stored into SD Card, now i have to send all SQLite data to server.
Note: I have created same fields to server database as well (simillar to SQLite DB) for an eg: PersonName
Below code i used to check, am i able to store data to server (for testing purpose - i accepted data by user into edittext) and then sent to server, and i was successful in that.
String url = "http://localhost/ChurchData.php";
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("sPersonName", editPersonName.getText().toString()));
String resultServer = getHttpPost(url,params);
Log.d("Entire string::", " " + resultServer);
/*** Default Value ***/
strStatusID = "0";
strError = "";
JSONObject c;
try {
c = new JSONObject(resultServer);
strStatusID = c.getString("StatusID");
strError = c.getString("Message");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// prepare save data
if(strStatusID.equals("0"))
{
Toast.makeText(getApplicationContext(), "Already Exist !", Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(getApplicationContext(), "Data Uploaded Successfully!", Toast.LENGTH_SHORT).show();
}
return true;
}
private String getHttpPost(String url,
List<NameValuePair> params) {
StringBuilder str = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
try {
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse response = client.execute(httpPost);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) { // Status OK
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
str.append(line);
}
} else {
Log.e("Log", "Failed to download result..");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return str.toString();
}
So may i know, How can i send SQLite database records to server ? My database class looks like this:
public class myDBClasss extends SQLiteOpenHelper {
// Database Version
private static final int DATABASE_VERSION = 2;
// Database Name
private static final String DATABASE_NAME = "ChurchDB";
// Table Name
private static final String TABLE_MEMBER = "DataTable";
public myDBClasss(Context context) {
// to store data into SD Card
super(context, Environment.getExternalStorageDirectory()
+ File.separator + "ChurchData"
+ File.separator + DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
// Create Table Name
db.execSQL("CREATE TABLE " + TABLE_MEMBER +
"(PersonName VARCHAR(100)," +
" PersonEmail VARCHAR(100)," +
" PersonTelephone VARCHAR(100)," +
" Newsletter VARCHAR(100));"); // checkbox
Log.d("CREATE TABLE","Create Table Successfully - classs");
}
// Insert Data
public long insertData(String strPersonName, String strPersonEmail, String strPersonTelephone, String strNewsletter) {
// TODO Auto-generated method stub
try {
SQLiteDatabase db;
db = this.getWritableDatabase(); // Write Data
ContentValues Val = new ContentValues();
Val.put("PersonName", strPersonName);
Val.put("PersonEmail", strPersonEmail);
Val.put("PersonTelephone", strPersonTelephone);
Val.put("Newsletter", strNewsletter); // checkbox
long rows = db.insert(TABLE_MEMBER, null, Val);
db.close();
return rows; // return rows inserted.
} catch (Exception e) {
return -1;
}
}
// Update Data
public long updateData(String strPersonName, String strPersonEmail, String strPersonTelephone, String strNewsletter){
// TODO Auto-generated method stub
try {
SQLiteDatabase db;
db = this.getWritableDatabase(); // Write Data
ContentValues Val = new ContentValues();
Val.put("PersonName", strPersonName);
Val.put("PersonEmail", strPersonEmail);
Val.put("PersonTelephone", strPersonTelephone);
Val.put("Newsletter", strNewsletter); // checkbox
long rows = db.update(TABLE_MEMBER, Val, "PersonName=?",
new String[] { String.valueOf(strPersonName) });
db.close();
return rows; // return rows updated.
} catch (Exception e) {
return -1;
}
}
// Fetch data
public String[] selectData(String strPersonName) {
// TODO Auto-generated method stub
try {
String arrData[] = null;
SQLiteDatabase db;
db = this.getReadableDatabase(); // Read Data
Cursor cursor = db.query(TABLE_MEMBER, new String[] { "*" },
"PersonName=?",
new String[] { String.valueOf(strPersonName) }, null, null, null, null);
if(cursor != null)
{
if (cursor.moveToFirst()) {
arrData = new String[cursor.getColumnCount()];
arrData[0] = cursor.getString(0);
arrData[1] = cursor.getString(1);
arrData[2] = cursor.getString(2);
arrData[3] = cursor.getString(3); // checkbox
}
}
cursor.close();
db.close();
return arrData;
} catch (Exception e) {
return null;
}
}
// Check for data(s) using PersonName field
public boolean exists(String strImageName) {
SQLiteDatabase db;
db = this.getReadableDatabase(); // Read Data
Cursor cursor = db.rawQuery("select 1 from DataTable where PersonName= ?",
new String[] { strImageName });
boolean exists = (cursor.getCount() > 0);
cursor.close();
return exists;
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS " + TABLE_MEMBER);
// Re Create on method onCreate
onCreate(db);
}
}
I think easy way is that you convert all your sqlite data into xml or json and then only one http request is required to send all your data to online server. At online server you can easily parse your data as you already know the structure of your xml or json whatever you used.
let say you have 2 fields in your database. ID , Name. you have 10 records. you convert all your records into json .
let say you query your database for all records and now cursor object will hold all your sqlite data.
add getAllData() method to retrieve all your database data.
public Cursor getAllData() {
String selectQuery = "Select * from "+TABLE_MEMBER;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
return cursor;
}
now do,
Cursor cursor = getAllData(); //cursor hold all your data
JSONObject jobj ;
JSONArray arr = new JSONArray();
cursor.moveToFIrst();
while(cursor.moveToNext()) {
jobj = new JSONObject();
jboj.put("Id", cursor.getInt("Id"));
jboj.put("Name", cursor.getString("Name"));
arr.put(jobj);
}
jobj = new JSONObject();
jobj.put("data", arr);
String st = jboj.toString();
now simply make an http call with string parameter and send to server.and parse at server by converting this string into jsonobject.
now according to your code, do
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("allData", st));
String resultServer = getHttpPost(url,params);
I have some snippet of code just for your idea.If it help you it my pleasure.
protected void startSync(Context aContext) {
try {
AccountManager am = AccountManager.get(getBaseContext());
Account[] ac = am.getAccountsByType(Constants.ACCOUNT_TYPE);
if (ac.length > 0) {
Toast.makeText(SuperHomeActivity.this,
"Synchronization Started", Toast.LENGTH_SHORT).show();
List<PeriodicSync> aList = ContentResolver.getPeriodicSyncs(
ac[0], Constants.AUTHORITY);
Bundle bundle = new Bundle();
bundle.putBoolean(ContentResolver.SYNC_EXTRAS_EXPEDITED, false);
if (aList != null && aList.size() > 0) {
while (aList != null && !aList.isEmpty()) {
ContentResolver.removePeriodicSync(ac[0],
Constants.AUTHORITY, aList.get(0).extras);
aList.remove(0);
}
}
// mention only in seconds -> 120 minutes 60 seconds
ContentResolver.addPeriodicSync(ac[0], Constants.AUTHORITY,
bundle, 5 * 60); //15
ContentResolver.requestSync(ac[0], Constants.AUTHORITY, bundle);
}
} catch (Exception ex) {
Log.e("SyncAccountTriggerError", ex.getMessage());
}
}
And you can call it by
startSync(getApplicationContext());
For any more clarification you can ping me.
you can use Http Post method or Get method or if you directly wants to update your server DB then use Put method. You can send data by http request with NameValue pair and just get that data from server and update your DB. That's it.
I'm facing a basic problem but i didn't find any tutorial in
order to help me...
I'm writing an application with sort of backup contact options. I want
that my applications works for android phones since 1.5 to 2.2
So i write a two implementation of ContactApi, one for 1.5, 1.6 and an
other for new api version.
Here is the list of problem I'm facing with.
With new api, nothing. All works fine, backing up contacts works well.
But with older api I'm not able to backing up some datas :
Email Datas (able to read, but not able to save)
IM datas (able to read, but not able to save)
Notes (able to read the first note, if many notes, I lost datas,
same things for backup)
Here is the code I'm using :
=======EMAIL=======
private ArrayList<Email> getEmailAddresses(String id) {
ArrayList<Email> emails = new ArrayList<Email>();
Cursor emailCur = this.contentResolver.query(Contacts.ContactMethods.CONTENT_EMAIL_URI, null, Contacts.ContactMethods.PERSON_ID + " = ?", new String[] { id }, null);
Email email = null;
while (emailCur.moveToNext()) {
// This would allow you get several email addresses
email = new Email();
email.setData(emailCur.getString(emailCur.getColumnIndex(Contacts.ContactMe thods.DATA)));
email.setType(emailCur.getInt(emailCur.getColumnIndex(Contacts.ContactMetho ds.TYPE)));
email.setLabel(emailCur.getString(emailCur.getColumnIndex(Contacts.PeopleCo lumns.NAME)));
emails.add(email);
}
emailCur.close();
return emails;
}
private void saveEmailAddresses(ContentUris contactUri, List<Email> emailList, String id) {
if (emailList != null && emailList.size() > 0) {
ContentValues values = null;
ContentValues[] valueArray = new ContentValues[emailList.size()];
int i = 0;
for (Email email : emailList) {
values = new ContentValues();
values.put(Contacts.ContactMethods.PERSON_ID, id); //
values.put(Contacts.ContactMethods.KIND, Contacts.KIND_EMAIL); //
values.put(Contacts.ContactMethods.DATA, email.getData()); //
values.put(Contacts.ContactMethods.TYPE, email.getType()); //
values.put(Contacts.PeopleColumns.NAME, email.getLabel()); //
valueArray[i] = values;
i++;
}
contentResolver.bulkInsert(Contacts.ContactMethods.CONTENT_EMAIL_URI, valueArray);
}
}
======== IM adress=============
private ArrayList<IM> getIM(Cursor cur, String id) {
ArrayList<IM> imList = new ArrayList<IM>();
String where = Contacts.ContactMethods.PERSON_ID + " = ? AND " + Contacts.ContactMethods.KIND + " = ?";
String[] whereParameters = new String[] { id,
String.valueOf(Contacts.KIND_IM) };
Cursor imCur =
this.contentResolver.query(Contacts.ContactMethods.CONTENT_URI, null,
where, whereParameters, null);
IM im = null;
while (imCur.moveToNext()) {
try {
String imName =
imCur.getString(imCur.getColumnIndex(Contacts.ContactMethodsColumns.DATA));
im = new IM();
im.setName(imName);
im.setType(imCur.getInt(imCur.getColumnIndex(Contacts.ContactMethodsColumns .TYPE)));
im.setProtocol(cur.getString(imCur.getColumnIndex(Contacts.ContactMethods.A UX_DATA)));
imList.add(im);
} catch (Exception e) {
Log.e(where, "Error im : ", e);
}
}
imCur.close();
return imList;
}
private void saveIM(List<IM> imList, String id) {
if (imList != null && imList.size() > 0) {
ContentValues values = null;
ContentValues[] valueArray = new ContentValues[imList.size()];
int i = 0;
for (IM im : imList) {
values = new ContentValues();
values.put(Contacts.ContactMethods.PERSON_ID, id); //
values.put(Contacts.ContactMethods.KIND, Contacts.KIND_IM); //
values.put(Contacts.ContactMethodsColumns.DATA, im.getName()); //
values.put(Contacts.ContactMethods.AUX_DATA,
ContactMethods.encodeCustomImProtocol(im.getProtocol())); //
values.put(Contacts.ContactMethodsColumns.TYPE, im.getType()); //
valueArray[i] = values;
i++;
}
contentResolver.bulkInsert(Contacts.ContactMethods.CONTENT_URI,
valueArray);
}
}
==========Notes =======
I have no idea how to get all notes ?
Can someone help me with this ?
public static HashMap Parse(String XML, String Tag, ArrayList<String> NodesList)
{
HashMap v = new HashMap();
try
{
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(XML));
Document doc = db.parse(is);
doc.getDocumentElement().normalize();
NodeList nodeLst = doc.getElementsByTagName(Tag);
nodeCount = nodeLst.getLength();
for (int s = 0; s < nodeCount; s++)
{
Node fstNode = nodeLst.item(s);
if (fstNode.getNodeType() == Node.ELEMENT_NODE)
{
Element fstElmnt = (Element) fstNode;
for(String nodeName : NodesList)
{
NodeList fstNmElmntLst = fstElmnt.getElementsByTagName(nodeName);
Element fstNmElmnt = (Element) fstNmElmntLst.item(0);
NodeList fstNm = fstNmElmnt.getChildNodes();
try {
String NodeValue = ((Node) fstNm.item(0)).getNodeValue().toString().trim();
if(NodeValue !=null )
v.put(nodeName + s, NodeValue);
}
catch(Exception e) {
v.put(nodeName + s, "");
}
}
}
}
}
catch (Exception e)
{
//e.printStackTrace();
}
return v;
}