Can't insert into JDBC oracleRowSet buttonGroup - netbeans-8

private void Acc_Button_createActionPerformed(java.awt.event.ActionEvent evt) {
int p = JOptionPane.showConfirmDialog(rootPane, "Do you want add", "Add", JOptionPane.YES_NO_OPTION);
if (p == 0) {
try {
String sql = "insert into ACCOUNT_INFO (ACC,NAMEF,DOB,PIN,ACCOUNT_TPAYE,NATIONALTY,CASTE,MICR_NO,GENDER,MOB_NO,ADDRESS,SEC_Q,SEC_A,BLANCE)values (?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
jrowSet.setCommand(sql);
jrowSet.setString(1, Acc_TextField_acc.getText());
jrowSet.setString(2, Acc_TextField_amunt.getText());
jrowSet.setString(3, ((JTextField) Acc_DateChooser_birh.getDateEditor().getUiComponent()).getText());
jrowSet.setString(4, Acc_TextField_pin.getText());
jrowSet.setString(5, (String) Acc_ComboBox_acc_type.getSelectedItem());
jrowSet.setString(6, (String) Acc_ComboBox_naton.getSelectedItem());
jrowSet.setString(7, Acc_TextField_name.getText());
jrowSet.setString(8, Acc_TextField_misr.getText());
// for radio btn
RadioButton_male.setActionCommand("Male");
RadioButton_female.setActionCommand("Femal");
// to insert radin in database
jrowSet.setString(9, buttonGroup2.getSelection().getActionCommand());
jrowSet.setString(10, Acc_TextField_caste.getText());
jrowSet.setString(11, Acc_TextField_adrres.getText());
jrowSet.setString(12, (String) Acc_ComboBox_sq_q.getSelectedItem());
jrowSet.setString(13, Acc_TextField_mob_no.getText());
jrowSet.setString(14, Acc_TextField_seq_a.getText());
jrowSet.execute();
// Bal();
JOptionPane.showMessageDialog(rootPane, "added", "add acount", JOptionPane.INFORMATION_MESSAGE);
} catch (HeadlessException | SQLException e) {
}
}
}
// Acc_Button_createActionPerformed(Account.java:414) >> this is the ine 414
jrowSet.setString(9, buttonGroup2.getSelection().getActionCommand());

Related

jvm condition and locksupport which is faster?

An experimental example of synchronous call is made. Each thread task waits for a task callback with its own value of + 1. The performance difference between condition and locksupport is compared. The result is unexpected. The two times are the same, but the difference on the flame diagram is very big. Does it mean that the JVM has not optimized locksupport
enter image description here
public class LockerTest {
static int max = 100000;
static boolean usePark = true;
static Map<Long, Long> msg = new ConcurrentHashMap<>();
static ExecutorService producer = Executors.newFixedThreadPool(4);
static ExecutorService consumer = Executors.newFixedThreadPool(16);
static AtomicLong record = new AtomicLong(0);
static CountDownLatch latch = new CountDownLatch(max);
static ReentrantLock lock = new ReentrantLock();
static Condition cond = lock.newCondition();
static Map<Long, Thread> parkMap = new ConcurrentHashMap<>();
static AtomicLong cN = new AtomicLong(0);
public static void main(String[] args) throws InterruptedException {
long start = System.currentTimeMillis();
for (int num = 0; num < max; num++) {
consumer.execute(() -> {
long id = record.incrementAndGet();
msg.put(id, -1L);
call(id);
if (usePark) {
Thread thread = Thread.currentThread();
parkMap.put(id, thread);
while (msg.get(id) == -1) {
cN.incrementAndGet();
LockSupport.park(thread);
}
} else {
lock.lock();
try {
while (msg.get(id) == -1) {
cN.incrementAndGet();
cond.await();
}
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
latch.countDown();
});
}
latch.await();
consumer.shutdown();
producer.shutdown();
System.out.printf("park %s suc %s cost %s cn %s"
, usePark
, msg.entrySet().stream().noneMatch(entry -> entry.getKey() + 1 != entry.getValue())
, System.currentTimeMillis() - start
, cN.get()
);
}
private static void call(long id) {
producer.execute(() -> {
try {
Thread.sleep((id * 13) % 100);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (usePark) {
msg.put(id, id + 1);
LockSupport.unpark(parkMap.remove(id));
} else {
lock.lock();
try {
msg.put(id, id + 1);
cond.signalAll();
} finally {
lock.unlock();
}
}
});
}
}

SCALA: executing complete .sql file

I have a .sql script files and need to execute complete .sql file at once, I have found many related answers, where programmer reads file and execute query one by one.
I require to run .sql file all at-once, like picking up the file and executing in within SCALA.
Currently I am doing it with following code, copied it from copied it from:https://gist.github.com/joe776/831762, my Lead ask me to do it in simple way, instead of executing script line by line, it should get executed as .SQL file
import java.io.IOException;
import java.io.LineNumberReader;
import java.io.PrintWriter;
import java.io.Reader;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ScriptRunner {
private static final String DEFAULT_DELIMITER = ";";
private static final String DELIMITER_LINE_REGEX = "(?i)DELIMITER.+";
private static final String DELIMITER_LINE_SPLIT_REGEX = "(?i)DELIMITER";
private final Connection connection;
private final boolean stopOnError;
private final boolean autoCommit;
private PrintWriter logWriter = new PrintWriter(System.out);
private PrintWriter errorLogWriter = new PrintWriter(System.err);
private String delimiter = DEFAULT_DELIMITER;
private boolean fullLineDelimiter = false;
/**
* Default constructor.
*
* #param connection
* #param autoCommit
* #param stopOnError
*/
public ScriptRunner(Connection connection, boolean autoCommit, boolean stopOnError) {
this.connection = connection;
this.autoCommit = autoCommit;
this.stopOnError = stopOnError;
}
/**
* #param delimiter
* #param fullLineDelimiter
*/
public void setDelimiter(String delimiter, boolean fullLineDelimiter) {
this.delimiter = delimiter;
this.fullLineDelimiter = fullLineDelimiter;
}
/**
* Setter for logWriter property.
*
* #param logWriter
* - the new value of the logWriter property
*/
public void setLogWriter(PrintWriter logWriter) {
this.logWriter = logWriter;
}
/**
* Setter for errorLogWriter property.
*
* #param errorLogWriter
* - the new value of the errorLogWriter property
*/
public void setErrorLogWriter(PrintWriter errorLogWriter) {
this.errorLogWriter = errorLogWriter;
}
/**
* Runs an SQL script (read in using the Reader parameter).
*
* #param reader
* - the source of the script
* #throws SQLException
* if any SQL errors occur
* #throws IOException
* if there is an error reading from the Reader
*/
public void runScript(Reader reader) throws IOException, SQLException {
try {
boolean originalAutoCommit = connection.getAutoCommit();
try {
if (originalAutoCommit != autoCommit) {
connection.setAutoCommit(autoCommit);
}
runScript(connection, reader);
} finally {
connection.setAutoCommit(originalAutoCommit);
}
} catch (IOException e) {
throw e;
} catch (SQLException e) {
throw e;
} catch (Exception e) {
throw new RuntimeException("Error running script. Cause: " + e, e);
}
}
/**
* Runs an SQL script (read in using the Reader parameter) using the connection passed in.
*
* #param conn
* - the connection to use for the script
* #param reader
* - the source of the script
* #throws SQLException
* if any SQL errors occur
* #throws IOException
* if there is an error reading from the Reader
*/
private void runScript(Connection conn, Reader reader) throws IOException, SQLException {
StringBuffer command = null;
try {
LineNumberReader lineReader = new LineNumberReader(reader);
String line = null;
while ((line = lineReader.readLine()) != null) {
if (command == null) {
command = new StringBuffer();
}
String trimmedLine = line.trim();
if (trimmedLine.startsWith("--")) {
println(trimmedLine);
} else if (trimmedLine.length() < 1 || trimmedLine.startsWith("//")) {
// Do nothing
} else if (trimmedLine.length() < 1 || trimmedLine.startsWith("--")) {
// Do nothing
} else if (!fullLineDelimiter && trimmedLine.endsWith(getDelimiter())
|| fullLineDelimiter && trimmedLine.equals(getDelimiter())) {
Pattern pattern = Pattern.compile(DELIMITER_LINE_REGEX);
Matcher matcher = pattern.matcher(trimmedLine);
if (matcher.matches()) {
setDelimiter(trimmedLine.split(DELIMITER_LINE_SPLIT_REGEX)[1].trim(),
fullLineDelimiter);
line = lineReader.readLine();
if (line == null) {
break;
}
trimmedLine = line.trim();
}
command.append(line.substring(0, line.lastIndexOf(getDelimiter())));
command.append(" ");
Statement statement = conn.createStatement();
println(command);
boolean hasResults = false;
if (stopOnError) {
hasResults = statement.execute(command.toString());
} else {
try {
statement.execute(command.toString());
} catch (SQLException e) {
e.fillInStackTrace();
printlnError("Error executing: " + command);
printlnError(e);
}
}
if (autoCommit && !conn.getAutoCommit()) {
conn.commit();
}
ResultSet rs = statement.getResultSet();
if (hasResults && rs != null) {
ResultSetMetaData md = rs.getMetaData();
int cols = md.getColumnCount();
for (int i = 0; i < cols; i++) {
String name = md.getColumnLabel(i);
print(name + "\t");
}
println("");
while (rs.next()) {
for (int i = 1; i <= cols; i++) {
String value = rs.getString(i);
print(value + "\t");
}
println("");
}
}
command = null;
try {
if (rs != null) {
rs.close();
}
} catch (Exception e) {
e.printStackTrace();
}
try {
if (statement != null) {
statement.close();
}
} catch (Exception e) {
e.printStackTrace();
// Ignore to workaround a bug in Jakarta DBCP
}
} else {
Pattern pattern = Pattern.compile(DELIMITER_LINE_REGEX);
Matcher matcher = pattern.matcher(trimmedLine);
if (matcher.matches()) {
setDelimiter(trimmedLine.split(DELIMITER_LINE_SPLIT_REGEX)[1].trim(),
fullLineDelimiter);
line = lineReader.readLine();
if (line == null) {
break;
}
trimmedLine = line.trim();
}
command.append(line);
command.append(" ");
}
}
if (!autoCommit) {
conn.commit();
}
} catch (SQLException e) {
e.fillInStackTrace();
printlnError("Error executing: " + command);
printlnError(e);
throw e;
} catch (IOException e) {
e.fillInStackTrace();
printlnError("Error executing: " + command);
printlnError(e);
throw e;
} finally {
conn.rollback();
flush();
}
}
private String getDelimiter() {
return delimiter;
}
private void print(Object o) {
if (logWriter != null) {
logWriter.print(o);
}
}
private void println(Object o) {
if (logWriter != null) {
logWriter.println(o);
}
}
private void printlnError(Object o) {
if (errorLogWriter != null) {
errorLogWriter.println(o);
}
}
private void flush() {
if (logWriter != null) {
logWriter.flush();
}
if (errorLogWriter != null) {
errorLogWriter.flush();
}
}
}
Why did you tag "scala"?
To execute a whole sql file at once:
sql < myFile.sql
Edit: as Cyrille Corpet pointed out, you can perform this command directly via scala
import sys.process._
"sql < myfile.sql" !

JSON response Using Volley in a recycler view in Android app

I am trying to print a json response response in a recyclerview. my Recyclerview is like a expanded listView. And my json resone is like this:
{"Table1":
[
{"filedate":"Oct 26, 2016"},
{"filedate":"Oct 18, 2016"}
],
"Table2":
[{
"filedate":"Oct 18, 2016",
"file1":"12.txt"
},
{
"filedate":"Oct 26, 2016",
"file1":"acerinvoice.pdf"
}
]}
and I trying to print this json resonse using this code:
private void prepareListData() {
// Volley's json array request object
StringRequest stringRequest = new StringRequest(Request.Method.POST, REGISTER_URL,
new Response.Listener<String>() {
//I think problrm is here
#Override
public void onResponse(String response) {
try {
**JSONObject object = new JSONObject(response);
JSONArray jsonarray = object.getJSONArray("Table1");
JSONArray jsonarray1 = object.getJSONArray("Table2");
for (int i = 0; i < jsonarray.length(); i++) {
try {
JSONObject obj = jsonarray.getJSONObject(i);
String str = obj.optString("filedate").trim();
int lth = jsonarray1.length();
data.add(new ExpandableListAdapter.Item(ExpandableListAdapter.HEADER, str));
for (int j = 0; j < jsonarray1.length(); j++) {
try {
JSONObject obj1 = jsonarray1.getJSONObject(j);
String str1 = obj1.optString("filedate").trim();
data.add(new ExpandableListAdapter.Item(ExpandableListAdapter.CHILD, str1));
Toast.makeText(getApplicationContext(), str1, Toast.LENGTH_LONG).show();**
//if condition
} catch (JSONException e) {
// Log.e(TAG, "JSON Parsing error: " + e.getMessage());
}
}
// adding movie to movies array
} catch (JSONException e) {
Log.e("gdshfsjkg", "JSON Parsing error: " + e.getMessage());
}
}
Log.d("test", String.valueOf(data));
Toast.makeText(getApplicationContext(), (CharSequence) data, Toast.LENGTH_LONG).show();
} catch (JSONException e) {
e.printStackTrace();
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
recyclerview.setAdapter(new ExpandableListAdapter(data));
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}){
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put(CLIENT, "4");
return params;
}
};
// Adding request to request queue
MyApplication.getInstance().addToRequestQueue(stringRequest);
}
ExpandableListAdapter
public class ExpandableListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
public static final int HEADER = 0;
public static final int CHILD = 1;
private List<Item> data;
public ExpandableListAdapter(List<Item> data) {
this.data = data;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int type) {
View view = null;
Context context = parent.getContext();
float dp = context.getResources().getDisplayMetrics().density;
int subItemPaddingLeft = (int) (18 * dp);
int subItemPaddingTopAndBottom = (int) (5 * dp);
switch (type) {
case HEADER:
LayoutInflater inflater = (LayoutInflater) parent.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.list_header, parent, false);
ListHeaderViewHolder header = new ListHeaderViewHolder(view);
return header;
case CHILD:
TextView itemTextView = new TextView(context);
itemTextView.setPadding(subItemPaddingLeft, subItemPaddingTopAndBottom, 0, subItemPaddingTopAndBottom);
itemTextView.setTextColor(0x88000000);
itemTextView.setLayoutParams(
new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT));
return new RecyclerView.ViewHolder(itemTextView) {
};
}
return null;
}
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
final Item item = data.get(position);
switch (item.type) {
case HEADER:
final ListHeaderViewHolder itemController = (ListHeaderViewHolder) holder;
itemController.refferalItem = item;
itemController.header_title.setText(item.text);
if (item.invisibleChildren == null) {
itemController.btn_expand_toggle.setImageResource(R.drawable.circle_minus);
} else {
itemController.btn_expand_toggle.setImageResource(R.drawable.circle_plus);
}
itemController.btn_expand_toggle.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (item.invisibleChildren == null) {
item.invisibleChildren = new ArrayList<Item>();
int count = 0;
int pos = data.indexOf(itemController.refferalItem);
while (data.size() > pos + 1 && data.get(pos + 1).type == CHILD) {
item.invisibleChildren.add(data.remove(pos + 1));
count++;
}
notifyItemRangeRemoved(pos + 1, count);
itemController.btn_expand_toggle.setImageResource(R.drawable.circle_plus);
} else {
int pos = data.indexOf(itemController.refferalItem);
int index = pos + 1;
for (Item i : item.invisibleChildren) {
data.add(index, i);
index++;
}
notifyItemRangeInserted(pos + 1, index - pos - 1);
itemController.btn_expand_toggle.setImageResource(R.drawable.circle_minus);
item.invisibleChildren = null;
}
}
});
break;
case CHILD:
TextView itemTextView = (TextView) holder.itemView;
itemTextView.setText(data.get(position).text);
break;
}
}
#Override
public int getItemViewType(int position) {
return data.get(position).type;
}
#Override
public int getItemCount() {
return data.size();
}
private static class ListHeaderViewHolder extends RecyclerView.ViewHolder {
public TextView header_title;
public ImageView btn_expand_toggle;
public Item refferalItem;
public ListHeaderViewHolder(View itemView) {
super(itemView);
header_title = (TextView) itemView.findViewById(R.id.header_title);
btn_expand_toggle = (ImageView) itemView.findViewById(R.id.btn_expand_toggle);
}
}
public static class Item {
public int type;
public String text;
public List<Item> invisibleChildren;
public Item() {
}
public Item(int type, String text) {
this.type = type;
this.text = text;
}
}
}
But this code print nothing in my recycler UI.It show only a empty layout.I have also tried to print the response in my log and it prints whole response together.I want to print table1 contents in headers and table2 contents in as child(items) with their respective headers.how to do this?If any other information needed please ask..
You should probably check your response first of everything. As per your requirements you should use HashMap and ArrayList. Follow these following steps:
1.Take a ArrayLsit and store child data of 1st heading and so on with index starting from 0.
2.Store headers in HashMap as key.
ex: HashMap<String,ArrayList<Data>> hm;
hm.put("your first heading string","related arraylist");
Then use ExpandableListView to arrange parent and child items.
please check your json response this is invalid json response first try to validate your json formate after try to decode and add in recycler view.
Check Your Response into Logcat also the Exception. I've tested the Response you've supplied that contains some unnecessary "," that may cause the Exception.
I have solve my problem to just change above code like this..
private void prepareListData() {
// Volley's json array request object
StringRequest stringRequest = new StringRequest(Request.Method.POST, REGISTER_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
JSONObject object = null;
try {
object = new JSONObject(response);
} catch (JSONException e) {
e.printStackTrace();
}
JSONArray jsonarray = null;
JSONArray jsonarray1 = null;
try {
jsonarray = object.getJSONArray("Table1");
jsonarray1 = object.getJSONArray("Table1");
} catch (JSONException e) {
e.printStackTrace();
}
for (int i = 0; i < jsonarray.length(); i++) {
try {
JSONObject obj = jsonarray.getJSONObject(i);
//
String str = obj.optString("filedate").trim();
Log.d("test", str);
data.add(new ExpandableListAdapter.Item(ExpandableListAdapter.HEADER, str));
// Toast.makeText(getApplicationContext(), lth, Toast.LENGTH_LONG).show();
for (int j = 0; j < jsonarray1.length(); j++) {
try {
JSONObject obj1 = jsonarray1.getJSONObject(j);
String str1 = obj1.optString("filedate").trim();
String str3 = obj1.optString("category").trim();
String str2 = obj1.optString("file1").trim();
String str4 = obj1.optString("4").trim();
Toast.makeText(getApplicationContext(), "server data respone", Toast.LENGTH_LONG).show();
Toast.makeText(getApplicationContext(), "test"+str1, Toast.LENGTH_LONG).show();
if (str == str1) {
// data.add(new ExpandableListAdapter.Item(ExpandableListAdapter.CHILD, str1));
data.add(new ExpandableListAdapter.Item(ExpandableListAdapter.CHILD, str3));
data.add(new ExpandableListAdapter.Item(ExpandableListAdapter.CHILD, str2));
}
Toast.makeText(getApplicationContext(), str1, Toast.LENGTH_LONG).show();
//if condition
} catch (JSONException e) {
// Log.e(TAG, "JSON Parsing error: " + e.getMessage());
}
}
// adding movie to movies array
} catch (JSONException e) {
Log.e("gdshfsjkg", "JSON Parsing error: " + e.getMessage());
}
}
Log.d("test", String.valueOf(data));
// notifying list adapter about data changes
// so that it renders the list view with updated data
// adapterheader.notifyDataSetChanged();
recyclerview.setAdapter(new ExpandableListAdapter(data));
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// VolleyLog.d(TAG, "Error: " + error.getMessage());
// hidePDialog();
}
}){
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put(CLIENT, "4");
return params;
}
};
// Adding request to request queue
MyApplication.getInstance().addToRequestQueue(stringRequest);
}

GCM IntentService

i used this code for GCM , but when i got pushnotification , i got error like this :
> 08-24 09:28:31.670 25605-5683/icon.apkt E/AndroidRuntime﹕ FATAL
> EXCEPTION: IntentService[GCMIntentService-43597399078-11]
> android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
> at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:5503)
> at android.view.ViewRootImpl.invalidateChildInParent(ViewRootImpl.java:1099)
> at android.view.ViewGroup.invalidateChildFast(ViewGroup.java:4417)
> at android.view.View.invalidateViewProperty(View.java:11201)
> at android.view.ViewPropertyAnimator$AnimatorEventListener.onAnimationUpdate(ViewPropertyAnimator.java:1047)
> at android.animation.ValueAnimator.animateValue(ValueAnimator.java:1166)
> at android.animation.ValueAnimator.animationFrame(ValueAnimator.java:1102)
> at android.animation.ValueAnimator.doAnimationFrame(ValueAnimator.java:1131)
> at android.animation.ValueAnimator$AnimationHandler.doAnimationFrame(ValueAnimator.java:616)
> at android.animation.ValueAnimator$AnimationHandler.run(ValueAnimator.java:639)
> at android.view.Choreographer$CallbackRecord.run(Choreographer.java:791)
> at android.view.Choreographer.doCallbacks(Choreographer.java:591)
> at android.view.Choreographer.doFrame(Choreographer.java:560)
> at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:777)
> at android.os.Handler.handleCallback(Handler.java:725)
> at android.os.Handler.dispatchMessage(Handler.java:92)
> at android.os.Looper.loop(Looper.java:137)
> at android.os.HandlerThread.run(HandlerThread.java:60)
Here is my code :
/**
* Method called on device un registred
*/
#Override
protected void onUnregistered(Context context, String registrationId) {
Log.i(TAG, "GCM Device unregistered");
generateNotification(context, "Device Unregistered", new Intent());
ServerUtilities.unregister(context, registrationId);
}
/**
* Method called on Receiving a new message
*/
#Override
protected void onMessage(final Context context, Intent intent) {
Log.i(TAG, "GCM Received message");
if (intent == null) {
} else {
String message = intent.getExtras().getString("message");
String namaPelanggan = "", alamat = "", telepon = "", noGangguan = "";
// {
// "reportNumber" : "G5313111100001"
// "status" : "Dalam Perjalanan",
// "poskoId" : "538711",
// "poskoName" : "POSKO DEPOK KOTA",
// "reguId" : "6683",
// "reguName" : "rdpk55",
// "idPel" : "525060659230",
// "namaPelanggan" : "SUPRIYADI" ,
// "createBy" : "11387",
// "createName" : "POSKODEPOK",
// "namaPelapor" : ""SAMINAH,
// "alamat" : "KP PANCORAN MAS",
// "telepon" : "021234234",
// "hp" : "081234234234",
// "longitude" : "0",
// "latitude" : "0"
// }
try {
JSONObject json = new JSONObject(message);
namaPelanggan = json.getString("namaPelanggan");
alamat = json.getString("alamat");
telepon = json.getString("telepon");
noGangguan = json.getString("reportNumber");
String total = "Gangguan baru diterima, NoGangguan = " + noGangguan
+ " Pelapor = " + namaPelanggan + ", Lokasi = " + alamat
+ ", Telepon = " + telepon;
// final String nogang = noGangguan;
try {
// GenericMethods.ShowToast(context, total);
User user = new User();
if (user.fromLocal(context)) {
GenericMethods.getGangguanOnline(context, user,
new onFinish() {
#Override
public void complete() {
// DO NOTHING
// Intent intent = null;
//
// Gangguan tugas = GenericMethods
// .getGangguan(nogang);
//
// if (tugas == null) {
// Log.i("RETURN", "NULL");
// return;
// }
//
// Log.i("SELECT", tugas.LASTSTATUS);
// if (tugas.LASTSTATUS
// .equalsIgnoreCase(WSDLConfig.status.status0))
// {
// intent = new Intent(context,
// BerangkatActivity.class);
// Log.d("GCM Open", tugas.LASTSTATUS);
// } else if (tugas.LASTSTATUS
// .equalsIgnoreCase(WSDLConfig.status.status1))
// {
// intent = new Intent(context,
// SebelumActivity.class);
// Log.d("GCM Open", tugas.LASTSTATUS);
// } else if (tugas.LASTSTATUS
// .equalsIgnoreCase(WSDLConfig.status.status2))
// {
// intent = new Intent(context,
// SesudahActivity.class);
// Log.d("GCM Open", tugas.LASTSTATUS);
// } else if (tugas.LASTSTATUS
// .equalsIgnoreCase(WSDLConfig.status.status3))
// {
// intent = new Intent(context,
// SesudahActivity.class);
// Log.d("GCM Open", tugas.LASTSTATUS);
// } else if (tugas.LASTSTATUS
// .equalsIgnoreCase(WSDLConfig.status.status4))
// {
// intent = new Intent(context,
// SelesaiActivity.class);
// Log.d("GCM Open", tugas.LASTSTATUS);
// }
//
// if (intent != null) {
// intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// intent.putExtra(
// Configuration.put_runworkflowID,
// tugas.REPORTNUMBER);
// startActivity(intent);
// }
// if (GenericMethods.activeActivity != null)
// ((MainActivity) GenericMethods.activeActivity)
// .getDaftarGangguanOffline();
}
});
}
} catch (Exception e) {
e.printStackTrace();
}
DBHelper db = new DBHelper(context);
db.insertGCMList(noGangguan, total);
db.close();
Log.i("GCM","GCM Notif");
generateNotification(getApplicationContext(), total, new Intent(
getApplicationContext(), MainActivity.class));
} catch (JSONException e) {
e.printStackTrace();
}
}
The exception is not about GCM, it is because you try to update your UI in intent service, intent service actually run in a separate thread. Android does not allow update UI in non-main thread.
Try to move your update UI code into main thread, here just an example:
new Handler(getMainLooper()).post(new Runnable() {
#Override
public void run() {
// put your update UI code here.
}
});

How to search the record in the sql adapter or datatable,

How to search the records in data-table,in my application I am having plenty of records.
For eg: After the searching completes I am getting 50 records out of 1000, from the table, now I want to do the first, next, previous and last record navigation for this searched records only. how can I do this, I have done for normal navigation(directly connecting to sql) but getting some difficulty in showing navigation in searched records.
try this
var results = from myRow in myDataTable.AsEnumerable()
where myRow.Field<int>("RowNo") == 1
select myRow;
Here i assume that you have fetched data into Datatable using "fetchData()" method.
// Global variable
DataTable dt_rec = new DataTable();
int rowCount = 1;
int lastRowNum = 0;
In the form_load event, you called the "fetchData()" method. After then you click on "Next" button click event which look like this.
private void NextButton_Click(System.Object sender, System.EventArgs e)
{
if (lastRowNum > rowCount) {
rowCount = rowCount + 1;
setControlValue(dt_rec.Rows(rowCount - 1));
} else {
Interaction.MsgBox("Record Not Found", "Test");
}
}
And here is the "Previous" button click event.
private void Previous_Click(System.Object sender, System.EventArgs e)
{
if (rowCount > 1) {
rowCount = rowCount - 1;
setControlValue(dt_rec.Rows(rowCount - 1));
} else {
Interaction.MsgBox("Record Not Found", "Test");
}
}
And here is the click event of "First" button.
private void FirstButton_Click(System.Object sender, System.EventArgs e)
{
if (rowCount != 1) {
rowCount = 1;
setControlValue(dt_rec.Rows(0));
} else {
Interaction.MsgBox("Record Not Found", "Test");
}
}
And finally the "Last" click event.
private void LastButton_Click(System.Object sender, System.EventArgs e)
{
if (rowCount < lastRowNum) {
rowCount = lastRowNum;
setControlValue(dt_rec.Rows(lastRowNum - 1));
} else {
Interaction.MsgBox("Record Not Found", "Test");
}
}
Here you find the setControlValue() method which will set the control value. For exa.
public void setControlValue(DataRow dr)
{
if (!string.IsNullOrEmpty(dr["UserId"])) {
txtUserName.Text = dr["UserId"].ToString();
}
if (!string.IsNullOrEmpty(dr["WebUrl"])) {
txtWebUrl.Text = dr["WebUrl"].ToString();
}
// and so on.....
}
Hope all these thing might help you...