I have declared strings string1, string2, string3, string4.. string7 in public class. and I am getting values from MySQL database using JSON in onCreate method and storing in String variables st1 , st2, st3...., st7.
Now I need to pass these st1 ,st2,st3,...,st7 values to the string1, string2, string3... string7 respectively.
public class MainActivity extends AppCompatActivity {
private Context mContext;
private Activity mActivity;
private CoordinatorLayout mCLayout;
private Button mButtonDo;
private TextView mTextView;
private String mJSONURLString = "http://paolo.....";
String string1, string2, string3, string4, string4, string5, string6, string7;
String seats = string1 + "" + string2 + "" + string3 + "" + string4 + "" + string5 + "" + string6 + "" + string7;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mContext = getApplicationContext();
mActivity = MainActivity.this;
mCLayout = (CoordinatorLayout) findViewById(R.id.coordinator_layout);
mTextView = (TextView) findViewById(R.id.tv);
mTextView.setText("");
RequestQueue requestQueue = Volley.newRequestQueue(mContext);
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.POST, mJSONURLString, null,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray seat) {
try {
// Loop through the array elements
for (int i = 0; i < seat.length(); i++) {
// Get current json object
JSONObject student = seat.getJSONObject(i);
String st1 = student.getString("st1");
String st2 = student.getString("st2");
String st3 = student.getString("st3");
String st4 = student.getString("st4");
String st5 = student.getString("st5");
String st6 = student.getString("st6");
String st7 = student.getString("st7");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue.add(jsonArrayRequest);
}
}
If you are getting the elements in the for loop as you are doing :
String st1 = student.getString("st1");
String st2 = student.getString("st2");
String st3 = student.getString("st3");
String st4 = student.getString("st4");
String st5 = student.getString("st5");
String st6 = student.getString("st6");
String st7 = student.getString("st7");
You should change it to :
string1 = student.getString("st1");
string2 = student.getString("st2");
string3 = student.getString("st3");
string4 = student.getString("st4");
string5 = student.getString("st5");
string6 = student.getString("st6");
string7 = student.getString("st7");
And if you want to update UI or something just add the method inside the onResponse() I mean if you want to display that text you can create a
private void showText(){
your_text_view1.setText(string1);
(....)
}
And then in the end of onResponse() just put this method.
Related
I need to convert a String[] to an JsonArray and I don't know how. I am new in android development i want to insert call log details in MySQL database. so, from android side i am getting an string and but I don't know how convert that string into Jsonarray. plz help to sort out this problem thanks in advance
Here is my java code.......
public class MainActivity extends Activity {
TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.lv);
getCallDetails();
}
private void getCallDetails()
{
StringBuffer sb = new StringBuffer();
String strOrder = android.provider.CallLog.Calls.DATE + " DESC";
Cursor managedCursor = managedQuery(CallLog.Calls.CONTENT_URI, null,null, null, strOrder);
int number1 = managedCursor.getColumnIndex(CallLog.Calls.NUMBER);
int type1 = managedCursor.getColumnIndex(CallLog.Calls.TYPE);
int duration1 = managedCursor.getColumnIndex(CallLog.Calls.DURATION);
sb.append("Call Log :");
while (managedCursor.moveToNext())
{
final String number = managedCursor.getString(number1);
final String type2 = managedCursor.getString(type1);
final String date = managedCursor.getString(managedCursor.getColumnIndexOrThrow("date")).toString();
java.util.Date date1 = new java.util.Date(Long.valueOf(date));
final String duration = managedCursor.getString(duration1);
String type = null;
Log.e("abc",date.toString());
Log.e("abc",date1.toString());
final String fDate = date1.toString();
int callcode = Integer.parseInt(type2);
switch (callcode)
{
case CallLog.Calls.OUTGOING_TYPE:
type = "Outgoing";
break;
case CallLog.Calls.INCOMING_TYPE:
type = "Incoming";
break;
case CallLog.Calls.MISSED_TYPE:
type = "Missed";
break;
}
sb.append("\nPhone Number:--- " + number + "");
sb.append(" \nCall Type:--- " + type + " ");
sb.append("\nCall Date:--- " + date1 + "");
sb.append ("\nCall duration in sec :--- " + duration);
sb.append("\n----------------------------------");
class getCallDetails extends AsyncTask<Void,Void,String>
{
#Override
protected String doInBackground(Void... params)
{
HashMap<String,String> param = new HashMap<String, String>();
param.put(Connect.KEY_NUMBER,number);
param.put(Connect.KEY_TYPE,type2);
param.put(Connect.KEY_DATE,fDate);
param.put(Connect.KEY_DURATION,duration);
RequestHandler rh = new RequestHandler();
String res = rh.sendPostRequest(Connect.URL_ADD, param);
return res;
}
}
getCallDetails idata = new getCallDetails();
idata.execute();
}
managedCursor.close();
textView.setText(sb);
}
}
Try this,
// Create JSONArray
JSONArray jArray = new JSONArray();
while (managedCursor.moveToNext())
{
final String number = managedCursor.getString(number1);
final String type2 = managedCursor.getString(type1);
final String date = managedCursor.getString(managedCursor.getColumnIndexOrThrow("date")).toString();
Date date1 = new Date(Long.valueOf(date));
final String fDate = date1.toString();
final String duration = managedCursor.getString(duration1);
String type = null;
// Create JSONObject
JSONObject item = new JSONObject();
// add the items to JSONObject
item.put("number", number);
item.put("type2", type2);
item.put("fDate", fDate);
item.put("duration", duration);
// add the JSONObject to JSONArray
jArray.put(item);
}
managedCursor.close();
System.out.println(jArray.toString());
It is easy.You can use one of the constructors of JSONArray class.
JSONArray jArr = new JSONArray(strArr)
where strArr is your String array.
More here: https://developer.android.com/reference/org/json/JSONArray.html#JSONArray(java.lang.Object)
I have been doing an app that needs a profile page. the login is an activity and the profile page is fragment. whenever I do the passing, it always returns null.
here is my MainActivity.java
public class MainActivity extends Activity {
ConnectionClass connectionClass;
EditText edtuserid,edtpass;
Button btnlogin;
ProgressBar pbbar;
public int test2;
public String test3 = "";
String user_fname;
String user_lname;
int dept_id;
String test;
String user_email;
String user_password;
String user_username;
Bundle profileBundle;
String userid;
String password;
int userIDD;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
connectionClass = new ConnectionClass();
edtuserid = (EditText) findViewById(R.id.edtuserid);
edtpass = (EditText) findViewById(R.id.edtpass);
btnlogin = (Button) findViewById(R.id.btnlogin);
pbbar = (ProgressBar) findViewById(R.id.pbbar);
pbbar.setVisibility(View.GONE);
edtuserid.setText(test3);
btnlogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
userid = edtuserid.getText().toString();
password = edtpass.getText().toString();
DoLogin doLogin = new DoLogin();
doLogin.execute("");
}
});
}
public class DoLogin extends AsyncTask<String,String,String>
{
int b;
String z = "";
Boolean isSuccess = false;
#Override
public void onPreExecute() {
pbbar.setVisibility(View.VISIBLE);
}
#Override
public void onPostExecute(String r) {
pbbar.setVisibility(View.GONE);
if(isSuccess) {
//DITO ANG REDIRECTION
Intent base = new Intent(MainActivity.this, OtherActivity.class);
startActivity(base);
finish();
}
}
#Override
public String doInBackground(String... params) {
if(userid.trim().equals("")|| password.trim().equals(""))
z = "Please enter User Id and Password";
else
{
try {
Connection con = connectionClass.CONN();
if (con == null) {
z = "Error in connection with SQL server";
} else {
String query = "select user_id, user_fname, user_lname, department_id, user_email, user_password, user_username from users where user_id='" + userid + "' and user_password='" + password + "'";
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
if(rs.next())
{
userIDD = rs.getInt(1);
Bundle profileBundle = new Bundle();
profileBundle.putInt("userID", userIDD);
PathfinderAdd fragobj = new PathfinderAdd();
fragobj.setArguments(profileBundle);
z = "The ID is " + userIDD;
isSuccess=true;
}
else
{
z = "Invalid Credentials";
isSuccess = false;
}
}
}
catch (Exception ex)
{
isSuccess = false;
z = "Error Somewhere";
Log.e("MYAPP", "exception", ex);
}
}
return z;
}
}
public String getMyData() {
String test4 = test3;
return test4;
}
}
And in the fragment, I retrieve the data as:
PathfinderAdd.java
public class PathfinderAdd extends Fragment {
ConnectionClass connectionClass;
EditText edtideaname, edtbenefit,edtobservation,edtquickwin,targetdate;
Button btnadd;
TextView targettv;
Spinner spinner1, spinner2;
ProgressBar pbbar;
String proid;
CalendarView calendar;
String realDate;
String DAY;
Date targ = null;
String finalDate;
SimpleDateFormat timeFormat;
java.sql.Date sql;
Date date2;
int userID = 0;
int user = 0;
public PathfinderAdd(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.addpathfinder, container, false);
connectionClass = new ConnectionClass();
edtideaname = (EditText) rootView.findViewById(R.id.edtideaname);
edtbenefit = (EditText) rootView.findViewById(R.id.edtbenefit);
edtobservation = (EditText) rootView.findViewById(R.id.edyobservation);
edtquickwin = (EditText) rootView.findViewById(R.id.edtquickwin);
targetdate = (EditText) rootView.findViewById(R.id.target);
spinner1 = (Spinner) rootView.findViewById(R.id.spinner1);
spinner2 = (Spinner) rootView.findViewById(R.id.spinner2);
btnadd = (Button) rootView.findViewById(R.id.btnadd);
pbbar = (ProgressBar) rootView.findViewById(R.id.pbbar);
targettv = (TextView) rootView.findViewById(R.id.tvtarget);
pbbar.setVisibility(View.GONE);
calendar = (CalendarView) rootView.findViewById(R.id.calendar1);
proid = "";
//String userId = ((MainActivity)getActivity()).IDD;
MainActivity getID = new MainActivity();
String IDD = getID.getMyData();
Toast.makeText(PathfinderAdd.this.getActivity(), IDD, Toast.LENGTH_SHORT).show();
btnadd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AddPro addPro = new AddPro();
addPro.execute("");
}
});
calendar.setOnDateChangeListener(new OnDateChangeListener() {
public void onSelectedDayChange(CalendarView view, int year_date, int month_date,
int dayOfMonth) {
int day = dayOfMonth;
int month = month_date;
int year = year_date;
DAY=String.valueOf(year)+String.valueOf(month)+String.valueOf(day);
}
});
return rootView;
}
public class AddPro extends AsyncTask<String, String, String> {
String z = "";
Boolean isSuccess = false;
String observation = edtobservation.getText().toString();
String quickwin = edtquickwin.getText().toString();
String ideaname = edtideaname.getText().toString();
String benefit = edtbenefit.getText().toString();
String target_date = targetdate.getText().toString();
String process = spinner1.getSelectedItem().toString();
String benefitType = spinner2.getSelectedItem().toString();
String lol = "2015-11-28";
Integer benefit_type = spinner2.getSelectedItemPosition();
Integer idea_type = spinner1.getSelectedItemPosition();
Integer idea_id;
Integer benefit_id;
Integer pathfinder_id = 1;
Integer pathfinder_status = 9;
Integer pathfinder_prog = 0;
#Override
protected void onPreExecute() {
pbbar.setVisibility(View.VISIBLE);
}
#Override
protected void onPostExecute(String r) {
pbbar.setVisibility(View.GONE);
Toast.makeText(PathfinderAdd.this.getActivity(), r, Toast.LENGTH_SHORT).show();
if(isSuccess==true) {
edtideaname.setText(null);
edtbenefit.setText(null);
edtobservation.setText(null);
edtquickwin.setText(null);
targetdate.setText(null);
}
}
#Override
protected String doInBackground(String... params) {
if (ideaname.trim().equals("") || benefit.isEmpty() || observation.trim().equals("") || quickwin.trim().equals(""))
z = "Please fill all the fields";
else {
try {
Connection con = connectionClass.CONN();
if (con == null) {
z = "Error in connection with SQL server";
} else {
//timeFormat = new SimpleDateFormat("yyyy-MM-dd",Locale.ENGLISH);
//finalDate = timeFormat.format(targ);
//sql = new java.sql.Date(targ.getTime());
int lol=1;
double benefitInt = Double.parseDouble(benefit);
date2 = new SimpleDateFormat("yyyyMMdd", Locale.ENGLISH).parse(DAY);
String newDateString = new SimpleDateFormat("yyyy/MM/dd",Locale.ENGLISH).format(date2);
DateFormat format2 = new SimpleDateFormat("yyyy/MM/dd", Locale.ENGLISH);
Date date3 = format2.parse(newDateString);
String dates = new SimpleDateFormat("yyyy/MM/dd", Locale.ENGLISH)
.format(Calendar.getInstance().getTime());
//String date = new SimpleDateFormat("yyyy/MM/dd", Locale.ENGLISH)
//.format(calendar.getDate());
switch (idea_type)
{
case 0:
idea_id = 1;
break;
case 1:
idea_id = 2;
break;
case 2:
idea_id = 3;
break;
case 3:
idea_id = 4;
break;
case 4:
idea_id = 5;
break;
default:
idea_id = 1;
break;
}
switch(benefit_type)
{
case 0:
benefit_id = 1;
break;
case 1:
benefit_id = 2;
break;
default:
benefit_id = 1;
break;
}
String query = "insert into pathfinder (pathfinder_id,pathfinder_name,idea_id,benefit_id,pathfinder_potential_eqv,pathfinder_observation,pathfinder_quickwin,pathfinder_target_closure,pathfinder_status,pathfinder_progress,patfinder_actual_closure,pathfinder_date_raised,user_id)" +
"values ('" +pathfinder_id+ "','" +ideaname+ "','" +idea_id+ "','" +benefit_id+ "','" +benefitInt+ "','" +observation+ "','" +quickwin+ "','" +dates+ "','" +pathfinder_status+ "','" +pathfinder_prog+ "','" +dates+ "','" +dates+ "','" + user+"')";
PreparedStatement preparedStatement = con.prepareStatement(query);
preparedStatement.executeUpdate();
z = "Added Successfully";
isSuccess = true;
}
} catch (Exception ex) {
isSuccess = false;
z = "Exceptions";
Log.e("MYAPP", "exception", ex);
}
}
return z;
}
}
}
the problem is that whenever this code executes, i get a null value. I have also tried assigning it to a method but it still returns null.
you must use same object for going to fragment. i think you used another object of fragment for transaction that's why it is showing null.
it have to be somewhat like this
PathfinderAdd fragobj = new PathfinderAdd();
fragobj.setArguments(profileBundle);
getSupportFragmentManager().beginTransaction().add(R.id.container , fragobj).commit();
You can also do this without passing data to fragment. You can directly get data from your main Activity like this. In your main Activity just do this.
if(rs.next())
{
userIDD = rs.getInt(1);
user_fname = rs.getString(2);
user_lname = rs.getString(3);
dept_id = rs.getInt(4);
user_email = rs.getString(5);
user_password = rs.getString(6);
user_username = rs.getString(7);
}
Then in your Fragment get values like this:
userId = ((YourActivity)getActivity()).userIDD;
Make sure your veriables are activity global.
If you are using a static fragment, setArguments() simply won't work. You need to set arguments for a transaction before you do a beginTransaction() in your fragmentManager. If you do it after that, then also setArguments() won't work
So each time I run the app, type in an ID and hit submit; the end result come outs with null as the ID.
For example: I want to type in 12345 it should go to http://www.hiddenlink.com/12345 but instead it goes to http://www.hiddenlink.com/null
Here's my code:
public class SearchActivity extends Activity {
Button btnSearchStudent;
String studentID;
private String url = "http://www.hiddenlink.com/" + studentID; // This is test SID just to confirm connection
private static final String TAG_ALLRECORDS = "Objects";
private static final String TAG_ENAME = "emer_name1";
private static final String TAG_EPHONE1 = "emer_Phone1";
private static final String TAG_EPHONE2 = "emer_Phone2";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
EditText txtStudentID = (EditText) findViewById(R.id.txtStudentID);
studentID = txtStudentID.getText().toString();
btnSearchStudent = (Button) findViewById(R.id.btnSearchSID);
btnSearchStudent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(SearchActivity.this, SearchResults.class);
startActivity(intent);
new JSONParse().execute();
}
});
}
private class JSONParse extends AsyncTask<Void, Void, Void> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(SearchActivity.this);
pDialog.setMessage("Connection Test: Logging into Student Database...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
// Login to APIs
#Override
protected Void doInBackground(Void... args) {
String _username = "hidden";
String _password = "hidden123";
String content = MyHttpURLConnection.getData(url, _username, _password);
try {
// Getting JSON Object from URL Content
JSONObject json = new JSONObject(content);
JSONArray jsonArray = json.getJSONArray(TAG_ALLRECORDS);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject c = jsonArray.getJSONObject(i);
// Storing JSON item in a Variable
String emer_name1 = c.getString(TAG_ENAME);
String emer_Phone1 = c.getString(TAG_EPHONE1);
String emer_Phone2 = c.getString(TAG_EPHONE2);
// Adding value HashMap key => value
HashMap<String, String> add = new HashMap<String, String>();
add.put(TAG_EPHONE1, emer_Phone1);
add.put(TAG_ENAME, emer_name1);
add.put(TAG_EPHONE2, emer_Phone2);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
}
}
String studentID;
private String url = "http://www.hiddenlink.com/" + studentID;
studentID hasn't been initialized here yet, and so its value is null. Remove the + studentID part and add the studentID when you have set it a value.
#Emd4600 is right
You must add the value only after edittext has been initialized and you have some value in it...
To do so do this just define the "url" var, but don't add student id to it:
private String url = "http://www.hiddenlink.com/%s";
And later when you get edittext do this add the id to url:
EditText txtStudentID = (EditText) findViewById(R.id.txtStudentID);
[... more code...]
String realUrl = String.format(url, txtStudentID.getText().toString(););
That's about it.
Why don't you just change your code with:
private String baseUrl = "http://www.hiddenlink.com/";
private String url = "";
btnSearchStudent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
url = baseUrl + txtStudentID.getText().toString();
new JSONParse().execute();
}
});
I'm missing the sense of reloding the whole Activity
You aren't re-assinging studentID after you click the button, hence it stays null because of its basic initialization:
btnSearchStudent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// re-init the student id field
CharSequence input = txtStudentId.getText();
if (input != null) {
studentID = input.toString();
}
Intent intent = new Intent(SearchActivity.this, SearchResults.class);
startActivity(intent);
new JSONParse().execute();
}
});
Code Standard
You should also label your global variables as m<Name> this is standard to signify that the field is a class member variable
Recommendation
Another way you can do this is to pass in the String into the execute() method of the AsyncTask, that way you can pass in multiple arguments instead of just one, but this will require that you change your AsyncTask to handle multiple queries.
As Emd4600 wrote, your String studentID is not initialized at the moment. You probably want to build and run your request when the user hits btnSearchStudent. To do so, you'll have to append the content of txtStudentId in the onClick listener of your button.
I used what Filnik said and it worked.
Thanks for all the input guys, much appreciated.
Filnik:
private String baseUrl = "http://www.hiddenlink.com/";
private String url = "";
btnSearchStudent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
url = baseUrl + txtStudentID.getText().toString();
new JSONParse().execute();
}
});
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)));
}
}
In my application I have three edit text and I am using shared preference to store those number. I want to fetch the numbers from shared preference and display in edit text and i want to edit the text also. When i run the below code i am getting NullPointerException. Can somebody help me?
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.change_cell_number);
init();
/*SharedPreferences sharedPref=this.getSharedPreferences("MY_PREF_2",MODE_WORLD_READABLE);
SharedPreferences.Editor shredPref_Editor=sharedPref.edit();
shredPref_Editor.putString(MY_ACTIVITY,"changeSMSnumber");
shredPref_Editor.commit();
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(ChangeSmsNumber_Activity.this);
String servername = settings.getString("sharedPreferencesKey", "defaultValue");
//server.setText(servername);
*/
btnSubmit.setOnClickListener(new OnClickListener()
{
#SuppressWarnings("unused")
#Override
public void onClick(View arg0)
{
// TODO Auto-generated method stub
String numberISD=edtxt_ISD_Code1.getText().toString();
if(edtxt_ISD_Code1.getText().toString().isEmpty())
{
Toast.makeText(getApplicationContext(),"Enter ISD 1st Number * ", Toast.LENGTH_SHORT).show();
}
else if(edtxt_Cell_Number1.getText().toString().isEmpty())
{
Toast.makeText(getApplicationContext(),"Enter 1st Number *", Toast.LENGTH_SHORT).show();
}
else
{
String strSign1 = edtxt_PlusSign1.getText().toString();
String strSign2 = edtxt_PlusSign2.getText().toString();
String strSign3 = edtxt_PlusSign3.getText().toString();
String strSign4 = edtxt_PlusSign4.getText().toString();
String strSign5 = edtxt_PlusSign5.getText().toString();
String strIsd1 = edtxt_ISD_Code1.getText().toString();
String strIsd2 = edtxt_ISD_Code2.getText().toString();
String strIsd3 = edtxt_ISD_Code3.getText().toString();
String strIsd4 = edtxt_ISD_Code4.getText().toString();
String strIsd5 = edtxt_ISD_Code5.getText().toString();
String strNum1 = edtxt_Cell_Number1.getText().toString();
String strNum2 = edtxt_Cell_Number2.getText().toString();
String strNum3 = edtxt_Cell_Number3.getText().toString();
String strNum4 = edtxt_Cell_Number4.getText().toString();
String strNum5 = edtxt_Cell_Number5.getText().toString();
String final_Num_1 = strSign1 + strIsd1 + strNum1;
String final_Num_2 = strSign2 + strIsd2 + strNum2;
String final_Num_3 = strSign3 + strIsd3 + strNum3;
String final_Num_4 = strSign4 + strIsd4 + strNum4;
String final_Num_5 = strSign5 + strIsd5 + strNum5;
SharedPreferences settings = ChangeSmsNumber_Activity.this.getSharedPreferences("MyPref_CellNumber",0);
strGetCellNum = settings.getString("num1", "n/a");
final_Num_1=strGetCellNum;
}
}
});
}
Please guide me.
sharedPref=this.getSharedPreferences("MY_PREF_2",MODE_PRIVATE);
String number= sharedPref.getString("KeyValue","defaultValue")//you can use defaultValue=""
For setting in Edittext
editText.setText(number);