i am executing sql query using JDBC driver but it gives me NetworkOnMainThreadException.i have used a Asyntask for the network operation and mention Internet permission in the menifest file. below is my code for executing query
public class getLedger extends AsyncTask<String, Void, Void> {
private ProgressDialog progressDlg;
private ResultSet rs;
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDlg = new ProgressDialog(LedgerActivity.this);
progressDlg.setMessage("Please wait...");
progressDlg.setIndeterminate(false);
progressDlg.setProgressStyle(android.R.style.Widget_ProgressBar_Small);
progressDlg.setCancelable(false);
progressDlg.show();
}
#Override
protected Void doInBackground(String... strings) {
SharedPreferences pref = getSharedPreferences("Login", Context.MODE_PRIVATE);
String ip = pref.getString("ip", "");
String username = pref.getString("username", "");
String password = pref.getString("password", "");
String dbname = pref.getString("dbname", "");
rs = new ExecuteQuery().selectdata(ip, username, password, strings[0], dbname);
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
try {
if (rs != null) {
ArrayList<Ledger> ledgerlist = new ArrayList<>();
while (rs.next()) {
String accode = rs.getString("AC_CODE");
String acname = rs.getString("AC_NAME");
String acaddr = rs.getString("AC_ADD1");
String acmobile = rs.getString("AC_MOBILE");
String actype = rs.getString("AC_TYPE");
String amount = rs.getString("Amount");
String goldwt = rs.getString("GoldWt");
String silverwt = rs.getString("SilverWt");
ledgerlist.add(new Ledger(accode, acname, acaddr, acmobile, actype, amount, goldwt, silverwt));
}
LedgerAdapter adapter = new LedgerAdapter(LedgerActivity.this, ledgerlist);
rcv_ledger.setAdapter(adapter);
}
} catch (SQLException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Looks like call to ResultSet.next() uses InputStream under the hood to load row value or something like that.
So to avoid exception you need to return ArrayList<Ledger> from doInBackground() instead of parsing ResultSet in onPostExecute()
Related
When I insert a sentence from my android phone, the data is not inserted to my database. But when I use my friend's mobile, it works successfully.
It actually does not work when I use space between two words. But, when I use a single word, it works.
I use VARCHAR in my database.
Here is my java code:
EditText cname, location, num, email, pass;
Button submit;
private static final String REGISTER_URL = "https://alex456.000webhostapp.com/Register.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
cname = (EditText)findViewById(R.id.editText8);
location = (EditText)findViewById(R.id.editText9);
num = (EditText)findViewById(R.id.editText10);
email = (EditText)findViewById(R.id.editText11);
pass = (EditText)findViewById(R.id.editText3);
submit = (Button) findViewById(R.id.button6);
submit.setOnClickListener(new View.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.CUPCAKE)
#Override
public void onClick(View v) {
registerUser();
}
});
}
private void registerUser(){
String CNAME, LOCATION, NUM, PASS ,EMAIL;
CNAME = cname.getText().toString().trim();
LOCATION = location.getText().toString().trim();
NUM = num.getText().toString().trim();
EMAIL = email.getText().toString().trim();
PASS = pass.getText().toString().trim();
register(CNAME, LOCATION, NUM, EMAIL, PASS);
}
private void register(String CNAME,String LOCATION,String NUM,String EMAIL, String PASS ) {
String urlSuffix = "?cnamePHP=" + CNAME + "&locationPHP=" + LOCATION + "&numPHP=" + NUM + "&emailPHP=" + EMAIL + "&passPHP=" + PASS;
class RegisterUser extends AsyncTask<String, Void, String> {
ProgressDialog loading;
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(RegisterActivity.this, "Please Wait", null, true, true);
}
#Override
protected String doInBackground(String... params) {
String s = params[0];
BufferedReader bufferedReader = null;
try {
URL url = new URL(REGISTER_URL + s);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String result;
result = bufferedReader.readLine();
return result;
} catch (Exception e) {
return null;
}
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
Intent i;
i = new Intent(RegisterActivity.this, RegisterActivity.class);
RegisterActivity.this.startActivity(i);
}
}
RegisterUser ur = new RegisterUser();
ur.execute(urlSuffix);
}
}
I am working on food ordering application as my project at school, and most of it is running smooth. The code that I will upload bellow works perfectly on the AVD and I can visualize it at my wampserver, however when using the same code on a real device it is not able to send the data. I changed the IP address to my local IP but it gives me an error pointing to the line
InputStream IS = httpURLConnection.getInputStream();
and
public class BackgroundTask extends AsyncTask
I will upload the codes in here in the hope that someone can help me.
Thanks in advance
This is my checkout basket where I send the data to the background task
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.checkout_basket_layout);
total_txt=(TextView)findViewById(R.id.total_txt);
total=(TextView)findViewById(R.id.total);
paypal=(ImageView)findViewById(R.id.paypal_btn);
paypal.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getBaseContext(), "FUNCTION DISABLED", Toast.LENGTH_LONG).show();
}
});
cancel = (Button)findViewById(R.id.cancel_order);
basket_menu=(Button)findViewById(R.id.menu_basket);
promocode=(Button)findViewById(R.id.promocode_btn);
enter_code=(EditText)findViewById(R.id.enter_code);
//List View
listView = (ListView) findViewById(R.id.checkout_list);
checkoutAdapter = new CheckoutAdapter(getApplicationContext(),R.layout.checkout_row_layout);
checkoutAdapter.notifyDataSetChanged();
listView.setAdapter(checkoutAdapter);
databaseOperations = new DatabaseOperations(getApplicationContext());
sqLiteDatabase = databaseOperations.getReadableDatabase();
cursor = databaseOperations.getInformation(sqLiteDatabase);
if (cursor.moveToFirst())
{
do{
String order, combo, juice;
String pricetxt;
Long price;
order = cursor.getString(0);
combo = cursor.getString(1);
juice=cursor.getString(2);
price= cursor.getLong(3);
BigDecimal price2= new BigDecimal(price);
BigDecimal price1;
BigDecimal cents = new BigDecimal(100);
price1= price2.divide(cents);
price1.setScale(2, BigDecimal.ROUND_CEILING);
pricetxt= price1.toString();
CheckoutDataProvider dataProvider = new CheckoutDataProvider(order, combo, pricetxt, juice);
checkoutAdapter.add(dataProvider);
}
while (cursor.moveToNext());
}
cur = databaseOperations.getTotal(sqLiteDatabase);
if(cur.moveToFirst())
{
do
{
Long total1;
String total_bill;
total1=cur.getLong(0);
BigDecimal total2= new BigDecimal(total1);
BigDecimal total3;
BigDecimal cents = new BigDecimal(100);
total3= total2.divide(cents);
total3.setScale(2, BigDecimal.ROUND_CEILING);
total_bill=total3.toString();
total.setText(total_bill);
}
while (cur.moveToNext());
}
}
public void back_menu (View view)
{
Intent intent=new Intent(CheckoutBasket.this,MainActivity.class);
startActivity(intent);
}
public void cancel_order (View view)
{
SQLiteDatabase sdb = databaseOperations.getWritableDatabase();
sdb.delete(OrderData.OrderInfo.TABLE_NAME, null, null);
sdb.execSQL("delete from " + OrderData.OrderInfo.TABLE_NAME);
sdb.close();
checkoutAdapter.notifyDataSetChanged();
Intent intent=new Intent(CheckoutBasket.this,MainActivity.class);
startActivity(intent);
}
public void use_promocode (View view)
{
databaseOperations = new DatabaseOperations(getApplicationContext());
sqLiteDatabase = databaseOperations.getReadableDatabase();
cursor = databaseOperations.getInformation(sqLiteDatabase);
if (cursor.moveToFirst())
{
do{
String order, combo, juice;
String pricetxt;
Long price;
order = cursor.getString(0);
combo = cursor.getString(1);
juice=cursor.getString(2);
price= cursor.getLong(3);
BigDecimal price2= new BigDecimal(price);
BigDecimal price1;
BigDecimal cents = new BigDecimal(100);
price1= price2.divide(cents);
price1.setScale(2, BigDecimal.ROUND_CEILING);
pricetxt= price1.toString();
String method = "register";
BackgroundTask backgroundTask=new BackgroundTask(this);
backgroundTask.execute(method,order,combo,juice,pricetxt);
}
while (cursor.moveToNext());
}
}
The next code is my background task
public class BackgroundTask extends AsyncTask<String, Void, String> {
Context ctx;
BackgroundTask(Context ctx)
{
this.ctx=ctx;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
String reg_url = "http://39.109.153.156/order/register.php";
String method = params [0];
if (method.equals("register"))
{
String order = params[1];
String combo =params[2];
String juice = params[3];
String pricetxt = params [4];
try {
URL url = new URL(reg_url);
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
Log.d("URLConnection", "Connection created");
OutputStream OS = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(OS, "UTF-8"));
String data = URLEncoder.encode("main","UTF-8") +"="+URLEncoder.encode(order,"UTF-8")+"&"+
URLEncoder.encode("combo","UTF-8") +"="+URLEncoder.encode(combo,"UTF-8")+"&"+
URLEncoder.encode("juice","UTF-8") +"="+URLEncoder.encode(juice,"UTF-8")+"&"+
URLEncoder.encode("pricetxt","UTF-8") +"="+URLEncoder.encode(pricetxt,"UTF-8");
bufferedWriter.write(data);
bufferedWriter.flush();
bufferedWriter.close();
Log.d("BufferedWriter", "Writer created");
OS.close();
InputStream IS = httpURLConnection.getInputStream();
IS.close();
return "Transaction Successful";
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(String result)
{
Toast.makeText(ctx, result, Toast.LENGTH_SHORT).show();
}
}
If I am no using the right tools to do that, can somebody please help me to point a way which I can follow?
Thanks to all
For it to work, you need to have your computer and device to use the same network (e.g the same wi-fi). If they are using the same network (wi-fi) then use Wireless LAN ipv4 address as your base url. e.g http://192.168.44.77/project
I am new to android development. I want to develop a android application that update data from a oracle database. Could anyone help me out?
Thanks in advance.
Use Apache Server to connect android to pc
In php.ini open oci8.dll
in htdocs make php file.
Your php code is
<?PHP
$con=
"(DESCRIPTION =
(ADDRESS = (PROTOCOL = TCP)(HOST = Your_ip)(PORT = 1521))
(CONNECT_DATA =(SERVER = DEDICATED)(SERVICE_NAME = Your_db_name)
)
)";
$conn = ocilogon( "User_name", "Password",$con,"WE8ISO8859P15");
$query = "select * from table_name";
$parseresults = ociparse($conn, $query);
ociexecute($parseresults);
while($row=oci_fetch_assoc($parseresults))
$output[]=$row;
print json_encode($output);
oci_free_statement($parseresults);
oci_close($conn);
?>
In android:
public class UploadActivity extends AsyncTask<Void, Void, String> {
Context context;
String result;
public UploadActivity(Context context) {
this.context = context;
}
#SuppressWarnings("static-access")
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(Void... params) {
// TODO Auto-generated method stub
final List<Pair<String, String>> postParameters = new ArrayList<>();
for (int i = 0; i < activity[0].length; i++) {
//postParameters.add(new Pair<>("var1", activity[i][0]);
result = null;
try {
String response = CustomHttpClient.execute(
URL + "Your_php.php", postParameters);
result = response.toString();
result = result.replaceAll("(\r\n|\n)", "");
} catch (Exception e) {
Log.e("log_tag_ms", "Error in http connection!!" + e.toString());
}
}
return null;
}
protected void onPostExecute(String result) {
super.onPostExecute(result);
} }
I do not know what to call this error. My app uses a self written shared preferences class. After a few times of running my app, nothing can be retrieved from my remote server. I'll post my shared preferences and one my my async tasks. There is no error within the logcat when the app does not retrieve anything.
Shared Preferences class:
public class SharedPreferences{
static final String PREF_USER_NAME = "username";
static final String PREF_USER_ID = "userid";
static android.content.SharedPreferences getSharedPreferences(Context ctx) {
return PreferenceManager.getDefaultSharedPreferences(ctx);
}
public static void setUserName(Context ctx, String userName)
{
Editor editor = getSharedPreferences(ctx).edit();
editor.putString(PREF_USER_NAME, userName);
editor.commit();
}
public static void setUserId(Context ctx, String userId)
{
Editor editor = getSharedPreferences(ctx).edit();
editor.putString(PREF_USER_ID, userId);
editor.commit();
}
public static String getUserName(Context ctx)
{
return getSharedPreferences(ctx).getString(PREF_USER_NAME, "");
}
public static String getUserId(Context ctx)
{
return getSharedPreferences(ctx).getString(PREF_USER_ID, "");
}
public static void clearUserName(Context ctx)
{
Editor editor = getSharedPreferences(ctx).edit();
editor.clear(); //clear all stored data
editor.commit();
}
}
Item retrieval async task:
public class GetEventsAsyncTask extends AsyncTask<String, Integer, Boolean>{
ProgressDialog progressDialog;
MainActivity activityMain;
List<Event> eventList = new ArrayList<Event>();
MyDbAdapter db;
public GetEventsAsyncTask(MainActivity parent)
{
activityMain = parent;
}
#Override
protected void onPreExecute() {
// progressDialog = null;
//
// if (progressDialog == null)
// {
// progressDialog = new ProgressDialog(activityMain);
// progressDialog.setMessage("download events, please wait...");
// progressDialog.show();
// progressDialog.setCanceledOnTouchOutside(false);
// progressDialog.setCancelable(false);
// }
}
#Override
protected Boolean doInBackground(String... params) {
// TODO Auto-generated method stub
Boolean error = false;
try {
error = postData(params[0]);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return error;
}
protected void onPostExecute(Boolean error){
/* if (progressDialog.isShowing()) {
progressDialog.dismiss();
progressDialog = null;
} */
if(error==true)
{
Log.i("GetEvents", "Error at get events");
activityMain.errorOccured();
}
else
{
Log.i("onPostExecute:eventlist.count",String.valueOf(eventList.size()));
MainActivity.myDB.removeAllEvents();
for(int i=0;i<eventList.size();i++)
{
MainActivity.myDB.insertEventEntry(eventList.get(i));
}
activityMain.downloadEventsSuccess(eventList);
// progressDialog.dismiss();
}
}
protected void onProgressUpdate(Integer... progress){
}
public Boolean postData(String user_id) throws JSONException {
Boolean error = false;
HttpClient httpclient = new DefaultHttpClient();
// specify the URL you want to post to
try {
Log.i("GetEvents", user_id);
HttpGet httpget = new HttpGet(Constants.HOST_NAME+"/"+Constants.SERVICE_NAME+"/api/Event?userId=" + user_id);
BufferedReader reader;
StringBuffer sb;
String line = "";
String NL="";
String json;
HttpResponse response = httpclient.execute(httpget);
if(response.getStatusLine().getStatusCode()==200)
{
reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
sb = new StringBuffer("");
line = "";
NL = System.getProperty("line.separator");
while ((line = reader.readLine()) != null)
{
sb.append(line + NL);
}
reader.close();
json = sb.toString();
Log.i("event json",json);
try
{
JSONArray jsonArray = new JSONArray(json);
for (int i = 0, length = jsonArray.length(); i < length; i++)
{
JSONObject attribute = jsonArray.getJSONObject(i);
Log.i("EventsAsync", attribute.toString(i));
Event eventObj = new Event();
eventObj.setEvent_id(attribute.getString("event_id"));
eventObj.setEvent_title(attribute.getString("event_title"));
eventObj.setEvent_desc(attribute.getString("event_desc"));
eventObj.setStart_date(attribute.getString("start_date"));
eventObj.setEnd_date(attribute.getString("end_date"));
eventObj.setStart_time(attribute.getString("start_time"));
eventObj.setEnd_time(attribute.getString("end_time"));
eventObj.setLocation(attribute.getString("location"));
eventObj.setPicture_path(attribute.getString("picture_path"));
eventObj.setSmall_picture_path(attribute.getString("small_picture_path"));
eventList.add(eventObj);
// DatabaseUser.openWritable();
// DatabaseUser.insertEvent(eventObj);
eventObj = null;
}
}
catch (JSONException e)
{
e.printStackTrace();
error = true;
}
}
else
{
error = true;
}
}
catch (ClientProtocolException e)
{
// process execption
error = true;
}
catch (IOException e)
{
// process execption
error = true;
}
return error;
}
}
Most of the time, the app stops retrieving after 3 times from onStart to onDestroy.
I've got a AsyncTask that will not finish when I have my lib.roomAvailable() call in the doInBackground method. When QueueTask is called a progressDialog will show and
it sticks. It should go away after 5 seconds.
If I remove lib.roomAvailable() from the doInBackground method everything work as expected. Why do I get this strange behaviour when I call lib.roomAvailable()?
roomAvailable() calls another AsyncTask can this be an issue?
public class QueueTask extends AsyncTask<Void, Void, Void> {
private ProgressDialog progressDialog;
private Library lib;
private String date;
private int room;
private int time;
private String user;
private String id;
public QueueTask(String date, int room, int time, String user, String id) {
this.date = date;
this.room = room;
this.time = time;
this.user = user;
this.id = id;
}
#Override
protected void onPreExecute() {
lib = new Library();
progressDialog = ProgressDialog.show(ManageRoomActivity.this, "Queuing", "Queuing process", true);
}
#Override
protected Void doInBackground(Void... params) {
int timer = 5;
while(timer > 0) {
if(lib.roomAvailable(date, room, time)) {
Log.w("RoomAvailable", "Room Available");
}
android.os.SystemClock.sleep(1000);
timer --;
Log.w("TIMER", "" + timer);
}
progressDialog.dismiss();
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
progressDialog.dismiss();
Intent intent = new Intent(ManageRoomActivity.this, DatePickerActivity.class);
ManageRoomActivity.this.startActivity(intent);
}
}
EDIT 1:
public boolean roomAvailable(String date, int room, int time) {
boolean available = false;
String timeString = "";
if(time < 10)
timeString = "0";
timeString = timeString + time;
String roomNum = "";
if(room < 10)
roomNum = "0";
roomNum = roomNum + room;
AsyncTask<String, Void, String> readSource = new URL_Source();
String source = "";
try {
String uri = getURI(date);
source = readSource.execute(getURI(date)).get();
String[] chunks = source.split("<td");
for(String chunk:chunks) {
if(chunk.contains(date) & chunk.contains("=Grp" + roomNum) & chunk.contains("stid=" + timeString))
available = true;
}
return available;
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
return available;
}
The other AsyncTask:
public final class URL_Source extends AsyncTask<String, Void, String> {
public URL_Source() {
}
protected String doInBackground(String... uri) {
try {
URL url = new URL(uri[0]);
InputStream in = url.openStream();
StringBuilder source = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line;
while((line = reader.readLine()) != null) {
source.append(line);
}
in.close();
return source.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "ERROR";
}
}
Solution:
I didn't have a clue how AsyncTask worked. You cannot call a AsynchTask within a AsyncTask!
You are attempting to create and start an AsyncTask from a thread other than the UI thread. That is not supported:
http://developer.android.com/reference/android/os/AsyncTask.html
See the section entitled "Threading Rules"