pass boolean from handler to function - android

I am trying to develop a function that gives my android application a test to see if the data on the phone matches that on the server.
I have every part of the function working fine apart from I want the message to come back from the server to the handler then I want the handler to return false or true and pass the value to function which returns a boolean.
A point in the right direction would be greatly appreciated.
here is the android code so far.
public boolean isTripUpladedToServer(int tripId)
{
if(isServiceRunning()&&tripId==currentTripId){return false;}
SQLiteDatabase db;
db=this.openOrCreateDatabase(DATABASE_NAME, SQLiteDatabase.OPEN_READWRITE, null);
String Qu="SELECT COUNT(tripid) from TRIP_DATA WHERE TRIPID="+tripId+";";
Cursor c= db.rawQuery(Qu, null);
int count=0;
if(c!=null &&c.moveToFirst())
{
count=c.getInt(0);
}
JSONArray parcel =new JSONArray();
JSONObject header =new JSONObject();
JSONObject message =new JSONObject();
try {
header.put("tablename", "isTripUploaded");
header.put("userid", userid);
parcel.put(header);
message.put("count", count);
message.put("tripid", tripId);
parcel.put(message);
Log.i(tag, parcel.toString());
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Handler inner=new Handler()
{
#Override
public void handleMessage(Message msg)
{
try {
JSONObject ret=new JSONObject(msg.obj.toString());
Log.i(tag,ret.toString());
// I want the function to return the boolean value that the server has sent to phone.
} catch (JSONException e) {
e.printStackTrace();
}
}
};
new uploadero(inner).execute(parcel);
//the below return value is here to prevent the error, ideally I want to remove it
return false;
}
If I have approached this in the wrong way please say, thanks in advance Mark

Use a class variable for the boolean and use a getter in the handler to get it.

Related

Why recyclerview adapter is not setting data properly?

Few days ago, I asked this question for avoiding repetition of reycylerview items whose accepted answer helped me to avoid data repetition.
But now I am facing new problems like: not showing all items sometimes only one like this . The real problem is even after getting all items from server properly data is not shown in recyclerView properly .Data are skipped randomly. I don't understand where the problem is. I even tried to use for loop instead of foreach but result was not different. Can anyone please help to fix this? It has been pain in the neck from last one week.
Code:
private List<TimelineData> timelineDataList=new ArrayList<>() ;
public void onCreateView(){
recyclerview.setLayoutManager(new LinearLayoutManager(ctx));
//Setting Adapter
adapter=new CustomRecyclerViewAdapter(timelineDataList);
recyclerview.setAdapter(adapter);
}
#Override
public void onStart() {
super.onStart();
// Fetching data from server
socket.disconnect();
socket.connect();
//Getting Data from server
JSONObject obj=new JSONObject();
try {
obj.put("timeline_posts","all");
socket.emit("data",obj);
} catch (JSONException e) {
e.printStackTrace();
}
}
void addTimelineData(String type,String time,String img_link){
boolean isRepeated = false;
for(TimelineData data : timelineDataList){
if(data.getTime().equals(time)){
isRepeated = true;
}
}
if(!isRepeated){
timelineDataList.add(new TimelineData(type,time,img_link));
}
adapter.notifyDataSetChanged();
}
private Emitter.Listener handlePosts = new Emitter.Listener(){
#Override
public void call(final Object... args){
try {
JSONArray jsonArray=(JSONArray)args[0];
timelineDataList.clear(); //clear data before inserting new one
for(int i=0;i<jsonArray.length();i++){
try {
JSONObject ob=jsonArray.getJSONObject(i);
post_type=ob.getString("post_type");
post_time=ob.getString("time");
post_link=ob.getString("img_link");
addTimelineData(post_type,post_time,post_link);
} catch (JSONException e) {
e.printStackTrace();
}
}
} catch (Exception e) {
Log.e("error",e.toString());
}
}
};
Adapter Code:
#Override
public void onBindViewHolder( CustomRecyclerViewHolder holder, int position) {
//Fetching TimelineData
TimelineData timelineData=totalList.get(position);
///Here I'm getting and converting array of image links which are there in jsonObject to arraylist
//Getting Imglink
Gson gson=new Gson();
Type type = new TypeToken<ArrayList<String>>() {}.getType();
ArrayList<String> arrayList = gson.fromJson(timelineData.getImg_link(), type);
//Setting ViewPager
CustomPagerAdapter adp=new CustomPagerAdapter(arrayList);
pager.setAdapter(new PagerAdapter() {
#Override
public int getCount() {
return 0;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return false;
}
});
holder.pager.setCurrentItem(position, false);
holder.pager.clearAnimation();
adp.notifyDataSetChanged();
holder.pager.setAdapter(adp);
holder.pager.setOffscreenPageLimit(1);
}
You are using notifyDataSetChnaged() very quickly, change notify method by this. So that you notify only selected item which you inserted.
Recommended method : You will put below code in your adapter and call this method from for loop where you were setting notifyDataSetChnaged here String s will be replaced by your model class. By this way you just notify only one element when inserting one element. This will also create some inserting animation automatically.
public void insertItemInList(String s) {
if (list == null) list = new ArrayList<>();
list.add(s);
notifyItemInserted(list.size() - 1);
}
Or
You can call notify outside for loop when your work is done like this.
for(int i=0;i<jsonArray.length();i++) {
try {
JSONObject ob=jsonArray.getJSONObject(i);
post_type=ob.getString("post_type");
post_time=ob.getString("time");
post_link=ob.getString("img_link");
addTimelineData(post_type,post_time,post_link);
} catch (JSONException e) {
e.printStackTrace();
}
}
adapter.notifyDataSetChanged();
Issue is that you are notifying adapter rapidly, it can also lead to UI inconsistency.
Let me know if this resolves your issue.
You are modifying the data list in the non-UI thread which could cause problems in the RecyclerView. Instead, you should collect all the data in tempTimelineDataList at once and update the adapted timelineDataList in the UI thread.

Get html from list of pages

I have list of web pages(over 100) with I have to vistit and collect data from.
I decided to save the html from all of them to one file, and then use Jsoup to find the interesting data.
But problem is to I do not know how to run 100 threads, and save the responses into one file, any ideas?
maybe it's not a masterpiece, but it works, and I wanted to make it as simple as possible.
ArrayList<String> links = new ArrayList<>();
Elements myDiv;
private void saveDetails() throws IOException {
if(repeat < links.size()){
repeat++;
textView.setText(String.valueOf(repeat));
saveFile(myDiv.toString());
myDiv = null;
getDetails(links.get(repeat));
}else {
textView.setText("finished");
}
}
private void getDetails(String urlStr) {
final String detailsUrl = urlStr;
new Thread() {
#Override
public void run() {
Message msg = Message.obtain();
try {
Document doc = Jsoup.connect(detailsUrl).get();
myDiv = doc.select(".exhibitor-contact");
} catch (IOException e1) {
e1.printStackTrace();
}
detailsHandler.sendMessage(msg);
}
}.start();
}
private Handler detailsHandler = new Handler() {
public void handleMessage(Message msg) {
super.handleMessage(msg);
try {
saveDetails();
} catch (IOException e) {
e.printStackTrace();
}
}
};
You don't need to save all of them in a file and then process them. You can gather information one by one. It is my suggestion:
arrayList urls = {100 site-url}; //in correct syntax
Document doc = null;
for (String url : urls) {
doc = Jsoup.connect(url).get();
//now proccess doc.toString as you want(in regular expression for example)
//save your desired information
}

ORMLite not update with the same count of object

I try to make simple test. I have json response from REST API with ~250 objects shops and the same response in file but first shop has different name. First step is load JSON file with ~250 shops and save in local db using ORMLite. Next step is connect with API and get the same response. New json response is parse and UPDATE exist elements in database. What is result?
Now I go to simple Activity with ListView and call getShopsAll(). This method return old data before update. Why?
This is method to save shop in database:
public void createShop(final ArrayList<ModelSklep> list) throws Exception {
getDaoShop().callBatchTasks(new Callable<Void>() {
#Override
public Void call() {
for(ModelSklep item : list) {
createShop(item);
if(item.getHoursList().size() > 0) {
createHours(item.getHoursList());
}
}
return null;
}
});
}
Method createshop:
public boolean createShop(ModelSklep item) {
try {
getDaoShop().createOrUpdate(item);
return true;
} catch (SQLException e) {
return false;
}
}
Method getShopAll:
public ArrayList<ModelSklep> getShopAll() {
try {
return (ArrayList<ModelSklep>) getDaoShop().queryBuilder().orderByRaw(
"nazwaPelna COLLATE LOCALIZED ASC").query();
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
Object is updating. But getShopAll() return old data object.
Clear cache after update doesn't work.
Help. I don't know how resolve this problem.
[Edit]
public Dao<ModelSklep, Integer> getDaoShop() {
if(modelShopDao == null) {
try {
modelShopDao = getDao(ModelSklep.class);
modelShopDao.setObjectCache(true);
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
return modelShopDao;
}

Only first word of two strings gets added to db

When trying to add words to a database via php, only the first word of both strings gets added.
I send the text via this code:
public void sendTextToDB() {
valcom = editText1.getText().toString();
valnm = editText2.getText().toString();
t = new Thread() {
public void run() {
try {
url = new URL("http://10.0.2.2/HB/hikebuddy.php?function=setcomm&comment="+valcom+"&name="+valnm);
h = (HttpURLConnection)url.openConnection();
if( h.getResponseCode() == HttpURLConnection.HTTP_OK){
is = h.getInputStream();
}else{
is = h.getErrorStream();
}
h.disconnect();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.d("Test", "CONNECTION FAILED 1");
}
}
};
t.start();
}
When tested with spaces and commas etc. in a browser, the php function adds all text.
The strings also return the full value when inserted into a dialog.
How do I fix this?
Thank you.
You need to URL-encode valcom and valnm when putting them into the URL.
See java.net.URLEncoder.encode: http://developer.android.com/reference/java/net/URLEncoder.html
url = new URL("http://10.0.2.2/HB/hikebuddy.php?function=setcomm&comment="
+ URLEncoder.encode(valcom)
+ "&name="+ URLEncoder.encode(valnm));

How save and get data in SQLite from two differen activity?

When my app is started, I get tiket from server that I use for sign response to server. This ticket (string) I save in database and when I run new response I get this tiket from database and attach to response. All was fine when I run responses from same activity where I save my ticket. I mean that when I am saving tiket, I also releases context of activity where I am executing this actions with database. BUT when I save tiket in one activity, launch another activity and try to get ticket from database in second activity, I get null (rown didn't contain item). So, can anybody tell me, where I'm erred?
I appreciate any help. Thank you.
Here code:
public long setTicket(Ticket ticket) throws SQLException {
ContentValues insertValues = new ContentValues();
insertValues.put(TicketTable.KEY_TICKET, ticket.getTicket());
insertValues.put(TicketTable.KEY_RESULT_CODE, ticket.getResultCode());
long result = m_db.insert(DATABASE_TABLE_TICKET, null, insertValues);
return result;
}
public Ticket getTicket() throws SQLException {
String[] columns = { TicketTable.KEY_ID, TicketTable.KEY_TICKET,
TicketTable.KEY_RESULT_CODE };
Cursor cursor = getCursor(DATABASE_TABLE_TICKET, columns);
Ticket result = new Ticket();
result.setTicket(cursor.getString(TicketTable.TICKET_COLUMN));
result.setResultCode(cursor.getString(TicketTable.RESULT_CODE_COLUMN));
cursor.close();
return result;
}
Here methods where I set access to database:
public String getTicket(){
DBAdapter adapter = new DBAdapter(m_context);
adapter.open();
String ticketEncoded = null;
Ticket ticket = null;
try {
ticket = adapter.getTicket();
ticketEncoded = java.net.URLEncoder.encode(ticket.getTicket());
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
adapter.close();
}
return ticketEncoded;
}
public void saveTicketFromServer(){
GetTicketHandler handler = new GetTicketHandler(m_context);
Ticket ticket = new Ticket();
ticket.setCommand("getTicket");
TicketTask task = new TicketTask(ticket);
createTask(task, handler);
}
And here I have caught null insted of ticket:
String comment = java.net.URLEncoder.encode(strToEncode, "UTF-8");
String barcodeId = "4605246006340";
String ball = "10";
String sign = account.getTicket();//here!
CreateCommentTask task = new CreateCommentTask(barcodeId, ball,
comment, sign);
//TODO create handler
HttpService httpService = new HttpService();
httpService.createTask(task, null);
But in another response all fine:
String sign = account.getTicket();
try {
task = new SearchBarcodeTask(searchForm, sign);
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
SearchBarcodeHandler handler = new SearchBarcodeHandler(m_activity);
HttpService httpService = new HttpService();
httpService.createTask(task, handler);
Alright the problem that I see is that String sign = account.getTicket();//here!
The account has to be null. So check what you are doing differently between the two other method calls you mentioned. You are doing something different with whatever account is.

Categories

Resources