dynamic list view with check box Issue? - java

I want to add checkbox to the dynamic list view which contains the price and text. The list displaying properly when iam trying to add checkbox action it displaying fetal error.
Here is the code.... Please help me out from this problem thanks in advance.
Adapter class:-
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CheckedTextView;
import android.widget.CompoundButton;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
class AdapterMenuList extends BaseAdapter {
private Activity activity;
ArrayList<AdapterMenuList> objects;
boolean box;
public AdapterMenuList(Activity act) {
this.activity = act;
}
public int getCount() {
// TODO Auto-generated method stub
return ActivityMenuList.sub_service_id.size();
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
AdapterMenuList getAdapterMenuList(int position) {
return ((AdapterMenuList) getItem(position));
}
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ViewHolder holder;
AdapterMenuList p = getAdapterMenuList(position);
if(convertView == null){
LayoutInflater inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.menu_list_item, null);
holder = new ViewHolder();
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
holder.txtText = (TextView) convertView.findViewById(R.id.txtText);
holder.txtSubText = (TextView) convertView.findViewById(R.id.txtSubText);
holder.ch = (CheckBox)convertView.findViewById(R.id.checkBox);
holder.txtText.setText(ActivityMenuList.sub_service_name.get(position));
holder.txtSubText.setText(ActivityMenuList.price.get(position)+" "+ ActivityMenuList.Currency);
holder.ch.setTag(position);
holder.ch.setChecked(p.box);
holder.ch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
getAdapterMenuList((Integer) buttonView.getTag()).box = isChecked;
}
});
return convertView;
}
ArrayList<AdapterMenuList> getBox() {
ArrayList<AdapterMenuList> box = new ArrayList<AdapterMenuList>();
for (AdapterMenuList p : objects) {
if (p.box)
box.add(p);
}
return box;
}
static class ViewHolder {
TextView txtText;
TextView txtSubText;
CheckBox ch;
}
}
List Activity.java:-
public class ActivityMenuList extends Activity {
ListView listMenu;
ProgressBar prgLoading;
//TextView txtTitle;
EditText edtKeyword;
ImageButton btnSearch;
TextView txtAlert;
// declare static variable to store tax and currency symbol
static double Tax;
static String Currency;
// declare adapter object to create custom menu list
AdapterMenuList mla;
// create arraylist variables to store data from server
static ArrayList<Long> sub_service_id = new ArrayList<Long>();
static ArrayList<String> sub_service_name = new ArrayList<String>();
static ArrayList<Double> price = new ArrayList<Double>();
String MenuAPI;
String TaxCurrencyAPI;
int IOConnect = 0;
long service_id;
String service_name;
String Keyword;
// create price format
DecimalFormat formatData = new DecimalFormat("#.##");
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.menu_list);
ActionBar bar = getActionBar();
bar.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.header)));
bar.setTitle("Product");
bar.setDisplayHomeAsUpEnabled(true);
bar.setHomeButtonEnabled(true);
prgLoading = (ProgressBar) findViewById(R.id.prgLoading);
listMenu = (ListView) findViewById(R.id.listMenu);
edtKeyword = (EditText) findViewById(R.id.edtKeyword);
btnSearch = (ImageButton) findViewById(R.id.btnSearch);
txtAlert = (TextView) findViewById(R.id.txtAlert);
// menu API url
MenuAPI = Constant.MenuAPI+"?accesskey="+Constant.AccessKey+"&service_id=";
// tax and currency API url
TaxCurrencyAPI = Constant.TaxCurrencyAPI+"?accesskey="+Constant.AccessKey;
// get category id and category name that sent from previous page
Intent iGet = getIntent();
service_id = iGet.getLongExtra("service_id",0);
service_name = iGet.getStringExtra("service_name");
MenuAPI += service_id;
// set category name to textview
// txtTitle.setText(Category_name);
mla = new AdapterMenuList(ActivityMenuList.this);
// call asynctask class to request tax and currency data from server
new getTaxCurrency().execute();
// event listener to handle search button when clicked
btnSearch.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
// TODO Auto-generated method stub
// get keyword and send it to server
try {
Keyword = URLEncoder.encode(edtKeyword.getText().toString(), "utf-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
MenuAPI += "&keyword="+Keyword;
IOConnect = 0;
listMenu.invalidateViews();
clearData();
new getDataTask().execute();
}
});
// event listener to handle list when clicked
listMenu.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long arg3) {
// TODO Auto-generated method stub
// go to menu detail page
String result = "Selected Product are :";
for (AdapterMenuList p : mla.getBox()) {
if (p.box){
result += "\n" + sub_service_name;
}
}
Toast.makeText(ActivityMenuList.this, result+"Total Amount:=" + sub_service_name, Toast.LENGTH_LONG).show();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_category, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
switch (item.getItemId()) {
case R.id.cart:
// refresh action
Intent iMyOrder = new Intent(ActivityMenuList.this, ActivityMenuList.class);
startActivity(iMyOrder);
overridePendingTransition (R.anim.open_next, R.anim.close_next);
return true;
case R.id.refresh:
IOConnect = 0;
listMenu.invalidateViews();
clearData();
new getDataTask().execute();
return true;
case android.R.id.home:
// app icon in action bar clicked; go home
this.finish();
overridePendingTransition(R.anim.open_main, R.anim.close_next);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
// asynctask class to handle parsing json in background
public class getTaxCurrency extends AsyncTask<Void, Void, Void>{
// show progressbar first
getTaxCurrency(){
if(!prgLoading.isShown()){
prgLoading.setVisibility(0);
txtAlert.setVisibility(8);
}
}
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
// parse json data from server in background
parseJSONDataTax();
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
// when finish parsing, hide progressbar
prgLoading.setVisibility(8);
// if internet connection and data available request menu data from server
// otherwise, show alert text
if((Currency != null) && IOConnect == 0){
new getDataTask().execute();
}else{
txtAlert.setVisibility(0);
}
}
}
// method to parse json data from server
public void parseJSONDataTax(){
try {
// request data from tax and currency API
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 15000);
HttpConnectionParams.setSoTimeout(client.getParams(), 15000);
HttpUriRequest request = new HttpGet(TaxCurrencyAPI);
HttpResponse response = client.execute(request);
InputStream atomInputStream = response.getEntity().getContent();
BufferedReader in = new BufferedReader(new InputStreamReader(atomInputStream));
String line;
String str = "";
while ((line = in.readLine()) != null){
str += line;
}
// parse json data and store into tax and currency variables
JSONObject json = new JSONObject(str);
JSONArray data = json.getJSONArray("data"); // this is the "items: [ ] part
JSONObject object_tax = data.getJSONObject(0);
JSONObject tax = object_tax.getJSONObject("tax_n_currency");
Tax = Double.parseDouble(tax.getString("Value"));
JSONObject object_currency = data.getJSONObject(1);
JSONObject currency = object_currency.getJSONObject("tax_n_currency");
Currency = currency.getString("Value");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
IOConnect = 1;
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// clear arraylist variables before used
void clearData(){
sub_service_id.clear();
sub_service_name.clear();
price.clear();
}
// asynctask class to handle parsing json in background
public class getDataTask extends AsyncTask<Void, Void, Void>{
// show progressbar first
getDataTask(){
if(!prgLoading.isShown()){
prgLoading.setVisibility(0);
txtAlert.setVisibility(8);
}
}
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
// parse json data from server in background
parseJSONData();
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
// when finish parsing, hide progressbar
prgLoading.setVisibility(8);
// if data available show data on list
// otherwise, show alert text
if(sub_service_id.size() > 0){
listMenu.setVisibility(0);
listMenu.setAdapter(mla);
}else{
txtAlert.setVisibility(0);
}
}
}
// method to parse json data from server
public void parseJSONData(){
clearData();
try {
// request data from menu API
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 15000);
HttpConnectionParams.setSoTimeout(client.getParams(), 15000);
HttpUriRequest request = new HttpGet(MenuAPI);
HttpResponse response = client.execute(request);
InputStream atomInputStream = response.getEntity().getContent();
BufferedReader in = new BufferedReader(new InputStreamReader(atomInputStream));
String line;
String str = "";
while ((line = in.readLine()) != null){
str += line;
}
// parse json data and store into arraylist variables
JSONObject json = new JSONObject(str);
JSONArray data = json.getJSONArray("data"); // this is the "items: [ ] part
for (int i = 0; i < data.length(); i++) {
JSONObject object = data.getJSONObject(i);
JSONObject menu = object.getJSONObject("Menu");
sub_service_id.add(Long.parseLong(menu.getString("sub_service_id")));
sub_service_name.add(menu.getString("sub_service_name"));
price.add(Double.valueOf(formatData.format(menu.getDouble("price"))));
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
//mla.imageLoader.clearCache();
listMenu.setAdapter(null);
super.onDestroy();
}
#Override
public void onConfigurationChanged(final Configuration newConfig)
{
// Ignore orientation change to keep activity from restarting
super.onConfigurationChanged(newConfig);
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
finish();
overridePendingTransition(R.anim.open_main, R.anim.close_next);
}
}
Main.XML:-
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#e7e7e7" >
<LinearLayout
android:id="#+id/lytSearch"
android:layout_width="fill_parent"
android:layout_height="45dp"
android:background="#color/header"
android:gravity="center_vertical"
android:visibility="visible" >
<EditText
android:id="#+id/edtKeyword"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginRight="10dp"
android:layout_marginLeft="5dp"
android:layout_weight="1"
android:background="#drawable/search_form"
android:hint="#string/search"
android:padding="7dp"
android:textColor="#color/hint"
android:textSize="14sp"
android:inputType="text"
android:singleLine="true" />
<ImageButton
android:id="#+id/btnSearch"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_weight="3"
android:background="#color/header"
android:src="#drawable/ic_search" />
</LinearLayout>
<ListView
android:visibility="gone"
android:id="#+id/listMenu"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/lytSearch"
android:divider="#null"
android:padding="5dp" />
<ProgressBar
android:id="#+id/prgLoading"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_centerInParent="true" />
<TextView
android:id="#+id/txtAlert"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/not_found"
android:textSize="14sp"
android:layout_centerInParent="true"
android:visibility="gone"/>
</RelativeLayout>
List_item.xml:-
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#e7e7e7"
android:padding="5dp" >
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/button_top_style_1"
android:orientation="vertical"
android:padding="5dp" >
<RelativeLayout
android:id="#+id/lytText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="5dp" >
<TextView
android:id="#+id/txtText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_toLeftOf="#+id/txtSubText"
android:maxLines="2"
android:text="aaa"
android:textSize="16sp" />
<TextView
android:id="#+id/txtSubText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:text="bbb" />
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="select"
android:id="#+id/checkBox"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:checked="false" />
</RelativeLayout>
</LinearLayout>
</RelativeLayout>
Error message:-
02-29 08:22:13.848 18814-18814/com.theredandblack.ecommerce E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.theredandblack.ecommerce, PID: 18814
java.lang.ClassCastException: java.lang.Integer cannot be cast to com.theredandblack.ecommerce.AdapterMenuList
at com.theredandblack.ecommerce.AdapterMenuList.getAdapterMenuList(AdapterMenuList.java:45)
at com.theredandblack.ecommerce.AdapterMenuList.getView(AdapterMenuList.java:50)
at android.widget.AbsListView.obtainView(AbsListView.java:2255)
at android.widget.ListView.measureHeightOfChildren(ListView.java:1263)
at android.widget.ListView.onMeasure(ListView.java:1175)
at android.view.View.measure(View.java:16497)
at android.widget.RelativeLayout.measureChild(RelativeLayout.java:689)
at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:473)
at android.view.View.measure(View.java:16497)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
at android.view.View.measure(View.java:16497)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
at com.android.internal.widget.ActionBarOverlayLayout.onMeasure(ActionBarOverlayLayout.java:327)
at android.view.View.measure(View.java:16497)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2291)
at android.view.View.measure(View.java:16497)
at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:1912)
at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1109)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1291)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:996)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5600)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:761)
at android.view.Choreographer.doCallbacks(Choreographer.java:574)
at android.view.Choreographer.doFrame(Choreographer.java:544)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:747)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5001)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)

The problem is with your getAdapterMenuList(int position) method. Your are returning ((AdapterMenuList) getItem(position)); which probablhy throws a ClassCastException as getItem returns an int which you are trying to cast to an AdapterMenuList

Related

How to populate a RecyclerView with data from a Service on Button click

I have this setup in my fragment. The user makes selections from the spinners and when they click the go button a service is initiated that is meant to get data and populate a recycler view with the data.The recycler view is located right below the spinners.The code is below.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp">
<Spinner
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/weekSpinner"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_margin="5dp">
</Spinner>
<Spinner
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/sessionSpinner"
android:layout_toRightOf="#+id/weekSpinner"
android:layout_toEndOf="#+id/weekSpinner"
android:layout_margin="5dp">
</Spinner>
<Spinner
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/termSpinner"
android:layout_toRightOf="#+id/sessionSpinner"
android:layout_toEndOf="#+id/sessionSpinner"
android:layout_margin="5dp">
</Spinner>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Go"
android:id="#+id/resultsSearch"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_margin="10dp"
android:layout_below="#+id/sessionSpinner"
android:textColor="#android:color/white"
android:background="#color/toolBar"/>
</RelativeLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/caRecycler">
</android.support.v7.widget.RecyclerView>
</LinearLayout>
</LinearLayout>
I am getting this error.
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object android.content.Context.getSystemService(java.lang.String)' on a null object reference
I understand that it has to do with the context being used but i have no idea how to solve it as this is the first time i'm using this sort of setup. Below is my fragment code.
public class caFragment extends Fragment
{
ArrayList<String> weeks,terms,sessions;
String selectedWeek,selectedTerm,selectedSession;
String activeChild;
Button go;
private static final String selectedChildTracker = "selectedChild";
SharedPreferences sharedpreferences;
static RecyclerView caDisplay = null;
static caCardAdapter cardAdapter = null;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.results_ca,null);
sharedpreferences = this.getActivity().getSharedPreferences(selectedChildTracker, Context.MODE_PRIVATE);
activeChild = sharedpreferences.getString("selectedChild",null);
final Spinner week,term,session;
setup();
week = (Spinner) view.findViewById(R.id.weekSpinner);
ArrayAdapter<String> weekAdapter = new ArrayAdapter<>(getContext(),android.R.layout.simple_spinner_item,weeks);
weekAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
week.setAdapter(weekAdapter);
term = (Spinner) view.findViewById(R.id.termSpinner);
ArrayAdapter<String> termAdapter = new ArrayAdapter<>(getContext(),android.R.layout.simple_spinner_item,terms);
termAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
term.setAdapter(termAdapter);
session = (Spinner) view.findViewById(R.id.sessionSpinner);
ArrayAdapter<String> sessionAdapter = new ArrayAdapter<>(getContext(),android.R.layout.simple_spinner_item,sessions);
sessionAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
session.setAdapter(sessionAdapter);
caDisplay = (RecyclerView) view.findViewById(R.id.caRecycler);
go = (Button) view.findViewById(R.id.resultsSearch);
go.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
selectedWeek = week.getSelectedItem().toString();
selectedTerm = term.getSelectedItem().toString();
selectedSession = session.getSelectedItem().toString();
Bundle extra = new Bundle();
extra.putString("selectedWeek",selectedWeek);
extra.putString("selectedTerm",selectedTerm);
extra.putString("selectedSession",selectedSession);
extra.putString("selectedChild",activeChild);
try
{
getActivity().startService(new Intent(getContext(), results.class).putExtras(extra));
}
catch (Exception ex)
{
System.out.print(ex);
}
}
});
return view;
}
public void setup()
{
weeks = new ArrayList<>();
terms = new ArrayList<>();
sessions = new ArrayList<>();
try
{
weeks.add("4");
weeks.add("8");
}
catch (Exception ex)
{
Log.e("Error adding weeks",ex.toString());
}
try
{
terms.add("First Term");
terms.add("Second Term");
terms.add("Third Term");
}
catch (Exception ex)
{
Log.e("Error adding terms",ex.toString());
}
try
{
sessions.add("2015/2016");
}
catch (Exception ex)
{
Log.e("Error adding sessions",ex.toString());
}
}
public void showResults()
{
cardAdapter = new caCardAdapter(getActivity(),cardResults.getResultSet());
caDisplay.setAdapter(cardAdapter);
caDisplay.setLayoutManager(new LinearLayoutManager(getActivity()));
}
}
and below is my service code
public class results extends Service
{
int mStartMode;
String tag_results_req = "tag_results_req";
static ArrayList<cardResults> cardResult;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
Bundle params = intent.getExtras();
Log.d("bundle param",params.toString());
String week = params.getString("selectedWeek");
String term = params.getString("selectedTerm");
String session = params.getString("selectedSession");
String child = params.getString("selectedChild");
makeRequest(week,term,session,child);
return mStartMode;
}
#Override
public void onDestroy()
{
super.onDestroy();
}
public void makeRequest(String week,String term,String session,String child)
{
String dataSet = week.trim()+","+term+","+session.trim()+","+child.trim();
byte[] data = new byte[0];
try
{
data = dataSet.getBytes("UTF-8");
}
catch (UnsupportedEncodingException e)
{
e.printStackTrace();
}
String query = Base64.encodeToString(data, Base64.DEFAULT);
Log.d("Query param",query);
//the url we are posting the request to
String url = " http://mobile.map.education/api/result/ca/"+query;
// prepare the Request
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>()
{
#Override
public void onResponse(JSONObject response)
{
// display response
Log.d("results",response.toString());
cardResults(response);
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error)
{
Log.e("Error.Response", error.toString());
Toast.makeText(getApplicationContext(),"Sorry there was an error getting results data",Toast.LENGTH_LONG).show();
}
}
);
queuer.getInstance().addToRequestQueue(request, tag_results_req);
}
public void cardResults(JSONObject result)
{
cardResult = new ArrayList<>();
JSONArray res = null;
try
{
res = (JSONArray) result.get("result_details");
Log.d("results",res.toString());
}
catch (Exception ex)
{
Log.e("error getting results",ex.toString());
}
for (int i = 0; i < res.length(); i++)
{
try
{
JSONObject subject = res.getJSONObject(i);
cardResults cardModel = new cardResults();
cardModel.setAverage("50");
cardModel.setScore(subject.getString("total"));
cardModel.setSubject(subject.getString("subject"));
cardModel.setAssignment(subject.getString("ASSIGNMENT"));
cardModel.setTest(subject.getString("CLASS TEST"));
cardModel.setWork(subject.getString("CLASS WORK"));
cardModel.setTeacher(subject.getString("teacher"));
cardResult.add(cardModel);
}
catch (Exception ex)
{
Log.e("card list",ex.toString());
}
}
try {
cardResults.setResultSet(cardResult);
caFragment m = new caFragment();
m.showResults();
}
catch (Exception ex)
{
Log.e("show result",ex.toString());
}
}
}
Looks like problem with your adapter which you are setting outside the onCreate of Fragment
cardAdapter = new caCardAdapter(getActivity());
caDisplay.setAdapter(cardAdapter);
caDisplay.setLayoutManager(new LinearLayoutManager(getActivity()));
move above lines inside the onCreate and just create one data Setter method in your Adapter class and then call this method to set data.
public void showResults()
{
//create setter method inside your adapter and notify
cardAdapter.setData(cardResults.getResultSet());
cardAdapter.notifyDataSetChanged();
}
before set Data just check that your data is not null!

btn.performClick() is not helping in triggerring button automatically

I want to trigger a button as soon as an OTP arrives and gets set in a edittext area field. OTP gets successfully set but submit button is not getting triggered itself. Where i am going wrong? Here is my code.
OTP.java
package com.nrb.app.nrb.otp;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.text.Editable;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextWatcher;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.nrb.app.nrb.HomeScreen;
import com.nrb.app.nrb.QRresponse.MyDBHelper;
import com.nrb.app.nrb.QRresponse.ServiceCalls;
import com.nrb.app.nrb.QRscanapi.RM;
import com.nrb.app.nrb.R;
import com.nrb.app.nrb.intera.AsyncResponseActivity;
import com.nrb.app.nrb.intera.ConnectionDetectorActivity;
import com.nrb.app.nrb.login.RegisterValidation;
import com.nrb.app.nrb.login.SignInActivity;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Set;
import uk.co.chrisjenx.calligraphy.CalligraphyContextWrapper;
public class OTP extends FragmentActivity implements View.OnClickListener {
private Hashtable<String, String> verifiedResponseKeyValue = new Hashtable<String, String>();
private Hashtable<String, String> verifiedNestedResponseKeyValue = new Hashtable<String, String>();
private String userMobValue;
private String otpVerUrl;
private String userNameValue;
private String userEmailValue;
private String userCountryValue;
private String userId;
private MyDBHelper myDBHelper;
private String userCountryCode;
private boolean timeOut;
static EditText OtpNumber;
private ConnectionDetectorActivity cd;
private String user_exist;
private Button OTP;
Context cntx;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_otp);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
cntx=this;
OtpNumber = (EditText) findViewById(R.id.etOTPVerifaction);
cd = new ConnectionDetectorActivity(OTP.this);
Bundle bundle = getIntent().getExtras();
userId=bundle.getString("id");
userEmailValue = bundle.getString("userEmailValue");
userMobValue = bundle.getString("userMobValue");
userNameValue = bundle.getString("userNameValue");
userCountryValue = bundle.getString("userCountryValue");
userCountryCode = bundle.getString("userCountryCode");
user_exist = bundle.getString("user_exist");
registerViews();
}
public void registerViews() {
OtpNumber = (EditText) findViewById(R.id.etOTPVerifaction);
// TextWatcher would let us check validation error on the fly
OtpNumber.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
RegisterValidation.isName(OtpNumber, false);
}
public void beforeTextChanged(CharSequence s, int start, int count, int after){}
public void onTextChanged(CharSequence s, int start, int before, int count){}
});
/* OtpNumber.setOnEditorActionListener(new EditText.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_DONE) {
OTP.performClick();
return true;
}
return false;
}
});*/
}
private boolean checkValidation() {
boolean ret = true;
if (!RegisterValidation.isName(OtpNumber, true))
ret = false;
return ret;
}
#SuppressLint("InflateParams")
private void popUpDialog(String result1, final boolean newuser) {
// TODO Auto-generated method stub
AlertDialog.Builder builder = new AlertDialog.Builder(OTP.this);
// Get the layout inflater
LayoutInflater inflater = OTP.this.getLayoutInflater();
View content = inflater.inflate(R.layout.otp_verification_dialog, null);
TextView tv = (TextView) content.findViewById(R.id.otpAlertMessage1);
tv.setText(result1);
builder.setView(content);
builder.setCancelable(false);
final AlertDialog alertDialog = builder.create();
alertDialog.show();
content.findViewById(R.id.btnOTPAlertOK).setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
alertDialog.dismiss();
if (newuser) {
Bundle bundle = new Bundle();
bundle.putString("defaultFrag", "newUserFrag");
Intent i = new Intent(OTP.this, HomeScreen.class);
i.putExtras(bundle);
startActivity(i);
setResult(10);
finish();
}
else{
Toast.makeText(cntx, "Please enter Valid OTP", Toast.LENGTH_LONG).show();
OtpNumber.setText("");
}
}
});
}
#SuppressLint("InflateParams")
private void popUpDialogSuccess(Spannable result1) {
// TODO Auto-generated method stub
AlertDialog.Builder builder = new AlertDialog.Builder(OTP.this);
// Get the layout inflater
LayoutInflater inflater = OTP.this.getLayoutInflater();
View content = inflater.inflate(R.layout.otp_verification_dialog, null);
TextView tv = (TextView) content.findViewById(R.id.otpAlertMessage1);
tv.setText(result1);
builder.setView(content);
builder.setCancelable(false);
final AlertDialog alertDialog = builder.create();
alertDialog.show();
content.findViewById(R.id.btnOTPAlertOK).setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
alertDialog.dismiss();
insertUserPfref();
}
});
}
public void verifyOTPKEY(View v) {
if (checkValidation()){
EditText etOTPVerification = (EditText) findViewById(R.id.etOTPVerifaction);
RM.OTP_VER_VALUE = etOTPVerification.getText().toString();
RM.OTP_MOB_VALUE = userMobValue;
if (user_exist.compareTo("true") == 0)
RM.OTP_USER_EXIST_VALUE = "true";
else
RM.OTP_USER_EXIST_VALUE = "false";
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put(RM.OTP_VER_KEY, RM.OTP_VER_VALUE);
jsonObject.put(RM.OTP_MOB_KEY, RM.OTP_MOB_VALUE);
jsonObject.put(RM.OTP_USER_EXIST_KEY, RM.OTP_USER_EXIST_VALUE);
jsonObject.put(RM.USER_Id_KEY,userId);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.d("==", "========= FAIL TO CREATE JSON ==========");
}
ServiceCalls Login = new ServiceCalls(this, RM.OTP_HOST,
jsonObject.toString(), "Verifying", 0, new AsyncResponseActivity() {
#Override
public void myAsyncResponse(String result) {
// TODO Auto-generated method stub
Log.d("==", "vvvvvvvvvvvvvvvvvvvvvvvvvvvvv");
Log.d("====>>>>", result);
parseOTPRsponseJason(result);
Log.d("==", "vvvvvvvvvvvvvvvvvvvvvvvvvvvvv");
}
});
if (cd.isConnectingToInternet()) {
Login.execute(1);
} else {
showNetworFailDialog(RM.NO_INTERNET_MSG);
}
}
else{
Toast.makeText(this, "Please enter OTP", Toast.LENGTH_LONG).show();
}
}
#Override
public void onClick(View v) {
}
class MyOTPAsyncTask extends AsyncTask<Void, Void, String> {
private ProgressDialog dialog;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
dialog = new ProgressDialog(OTP.this);
dialog.setMessage("Authenticating...");
dialog.show();
}
#Override
protected String doInBackground(Void... params) {
StringBuilder stringBuilder = new StringBuilder();
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(otpVerUrl);
try {
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
InputStream inputStream = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
}
inputStream.close();
} catch (Exception e) {
timeOut = true;
Log.d("readJSONFeed", e.getLocalizedMessage());
}
return stringBuilder.toString();
}
#Override
protected void onPostExecute(String result) {
dialog.dismiss();
// popUpDialog(result);
if (!timeOut)
parseOTPRsponseJason(result);
else
showNetworFailDialog(RM.REQ_TIMEOUT_MSG);
Log.d("----->", " Response " + result);
}
}
private void parseOTPRsponseJason(String result) {
// TODO Auto-generated method stub
JSONObject json;
JSONObject nestedJson;
try {
json = new JSONObject(result);
Iterator<String> iter = json.keys();
while (iter.hasNext()) {
String key = iter.next();
Object value = json.get(key);
if (user_exist.compareTo("true") == 0) {
if (key.compareTo("responseHash") == 0) {
nestedJson = new JSONObject(json.get(key).toString());
Iterator<String> nestedIter = nestedJson.keys();
while (nestedIter.hasNext()) {
String nestedKey = nestedIter.next();
Object nestedValue = nestedJson.get(nestedKey);
verifiedNestedResponseKeyValue.put(nestedKey,
nestedValue.toString());
}
}
}
verifiedResponseKeyValue.put(key, value.toString());
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
Set<String> hKeys2 = verifiedResponseKeyValue.keySet();
for (String string : hKeys2) {
Log.d("====>",
string + " ==>" + verifiedResponseKeyValue.get(string));
}
String x = verifiedResponseKeyValue.get("success");
if (x.compareTo("true") == 0) {
if (user_exist.compareTo("true") == 0) {
userNameValue = verifiedNestedResponseKeyValue.get("name");
Spannable wordtoSpan = new SpannableString("HI "
+ userNameValue + " , Welcome back to Onspot");
wordtoSpan.setSpan(new ForegroundColorSpan(Color.RED), 3,
3 + userNameValue.length(),
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
popUpDialogSuccess(wordtoSpan);
} else {
Spannable wordtoSpan = new SpannableString(
"Congratulations! " + userNameValue
+ " , you are successfully registered.");
wordtoSpan.setSpan(new ForegroundColorSpan(Color.RED), 17,
17 + userNameValue.length(),
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
popUpDialogSuccess(wordtoSpan);
}
} else
popUpDialog(
verifiedResponseKeyValue.get("responseMessage"), false);
} catch (Exception e) {
// TODO Auto-generated catch block
Log.d("====>", "Exception");
popUpDialog(RM.CrashError, false);
}
}
private void insertUserPfref() {
// TODO Auto-generated method stub
myDBHelper = new MyDBHelper(OTP.this);
myDBHelper.getWritableDatabase();
if (user_exist.compareTo("true") == 0) {
try {
myDBHelper.insertRegisteredUser(
verifiedNestedResponseKeyValue.get("email"), //
verifiedNestedResponseKeyValue.get("mobile_number"),//
verifiedNestedResponseKeyValue.get("name"), //
verifiedNestedResponseKeyValue.get("country"),
//
verifiedNestedResponseKeyValue.get("country_code"));
} catch (Exception e) {
// TODO Auto-generated catch block
Log.d("====>", "Exception");
popUpDialog(RM.CrashError, false);
}
Log.d("------>", "Existing USER");
Log.d("------>", "Existing USER" + user_exist);
} else {
myDBHelper.insertRegisteredUser(userEmailValue,//
userMobValue,//
userNameValue, //
userCountryValue,//
userCountryCode);
Log.d("------>", "New User");
Log.d("------>", "New User" + user_exist);
}
Log.d("------>", user_exist);
startActivity(new Intent(OTP.this, HomeScreen.class));
setResult(10);
finish();
}
#SuppressLint("InflateParams")
private void showNetworFailDialog(String msg) {
// TODO Auto-generated method stub
AlertDialog.Builder builder = new AlertDialog.Builder(OTP.this);
// Get the layout inflater
LayoutInflater inflater = OTP.this.getLayoutInflater();
View content = inflater.inflate(R.layout.network_failure_dialog, null);
builder.setView(content);
builder.setCancelable(false);
final AlertDialog alertDialog = builder.create();
alertDialog.show();
TextView tvMsg = (TextView) content.findViewById(R.id.networkFailMsg);
tvMsg.setText(msg);
content.findViewById(R.id.btnNetworkFailureOK).setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
alertDialog.dismiss();
setResult(10);
finish();
}
});
}
#Override
public void onBackPressed() {
Intent i = new Intent(OTP.this, SignInActivity.class);
startActivity(i);
setResult(10);
finish();
}
#Override
public boolean onTouchEvent(MotionEvent event) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
return true;
}
#Override
protected void attachBaseContext(Context newBase) {
super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase));
}
public void recivedSms(String message)
{
try
{
int pos=message.indexOf(':');
String msg = message.substring(pos + 2);
OtpNumber.setText(msg);
OTP = (Button) findViewById(R.id.btnOTPVerify);
OTP.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Do something in response to button click
}
});
OTP.performClick();
OTP.setPressed(true);
/* if(OtpNumber!=null) {
if (checkValidation()) {
EditText etOTPVerification = (EditText) findViewById(R.id.etOTPVerifaction);
RM.OTP_VER_VALUE = etOTPVerification.getText().toString();
RM.OTP_MOB_VALUE = userMobValue;
if (user_exist.compareTo("true") == 0)
RM.OTP_USER_EXIST_VALUE = "true";
else
RM.OTP_USER_EXIST_VALUE = "false";
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put(RM.OTP_VER_KEY, RM.OTP_VER_VALUE);
jsonObject.put(RM.OTP_MOB_KEY, RM.OTP_MOB_VALUE);
jsonObject.put(RM.OTP_USER_EXIST_KEY, RM.OTP_USER_EXIST_VALUE);
jsonObject.put(RM.USER_Id_KEY, userId);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.d("==", "========= FAIL TO CREATE JSON ==========");
}
ServiceCalls Login = new ServiceCalls(this, RM.OTP_HOST,
jsonObject.toString(), "Verifying", 0, new AsyncResponseActivity() {
#Override
public void myAsyncResponse(String result) {
// TODO Auto-generated method stub
Log.d("==", "vvvvvvvvvvvvvvvvvvvvvvvvvvvvv");
Log.d("====>>>>", result);
parseOTPRsponseJason(result);
Log.d("==", "vvvvvvvvvvvvvvvvvvvvvvvvvvvvv");
}
});
if (cd.isConnectingToInternet()) {
Login.execute(1);
} else {
showNetworFailDialog(RM.NO_INTERNET_MSG);
}
} else {
Toast.makeText(this, "Please enter OTP", Toast.LENGTH_LONG).show();
}
}*/
}
catch (Exception e)
{
}
}
}
IncomingMsg.java
package com.nrb.app.nrb.otp;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.telephony.SmsMessage;
import android.util.Log;
/**
* Created by Neha on 07-03-2016.
*/
public class IncomingMsg extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent)
{
final Bundle bundle = intent.getExtras();
try {
if (bundle != null)
{
final Object[] pdusObj = (Object[]) bundle.get("pdus");
for (int i = 0; i < pdusObj.length; i++)
{
SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) pdusObj[i]);
String phoneNumber = currentMessage.getDisplayOriginatingAddress();
String senderNum = phoneNumber ;
String message = currentMessage.getDisplayMessageBody();
try
{
if (senderNum.equals("DZ-Onspot"))
{
OTP Sms = new OTP();
Sms.recivedSms(message );
}
}
catch(Exception e){}
}
}
} catch (Exception e)
{
}
}
}
activity_otp.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:ripple="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="25dp"
android:gravity="center"
android:orientation="vertical"
android:background="#fff"
android:padding="10dp" >
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/onspot" />
<EditText
android:id="#+id/etOTPVerifaction"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="25dp"
android:inputType="textCapCharacters"
android:ems="10"
android:hint="Enter Verification Key"
android:maxLength="10"
android:singleLine="true">
</EditText>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:gravity="center_horizontal"
android:orientation="horizontal"
android:padding="5dp"
android:onClick="verifyOTPKEY">
<com.andexert.library.RippleView
android:id="#+id/ripple1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:rv_rippleDuration="200"
app:rv_type="rectangle" >
<Button
android:id="#+id/btnOTPVerify"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/button_shadow"
android:text="SUBMIT"
android:onClick="verifyOTPKEY"
android:textColor="#color/white" />
</com.andexert.library.RippleView>
</LinearLayout>
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:onClick="verifyOTP"
android:text="Enter Verification key For Login"
android:textAppearance="?android:attr/textAppearanceSmall" />
You're setting it to do nothing. You should comment out these line
OTP.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Do something in response to button click
}
});
Have you tried putting performClick inside Runnable like this,
OTP.post(new Runnable(){
#Override
public void run() {
OTP.performClick();
}
});
OR
Use view tree observer which is used to register listeners that can be notified of global changes in the view tree like here which is efficient in higher level of api than 16
ViewTreeObserver vt = OTP.getViewTreeObserver();
vt.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
vt.removeOnGlobalLayoutListener(this);
OTP.performClick();
}
});

Server Side Android Application failing to start

this is my first question and ive been stuck on this unknown problem for day now. The app was running successfully till i added some new code to make a custom listview component and to read some messages from the client.
The MainActivity.java
`public class MainActivity extends Activity {
TextView info, infoip, msg;
String message = "";
ServerSocket serverSocket;
ArrayList<String> list = new ArrayList<String>();
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
private GoogleApiClient client;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
info = (TextView) findViewById(R.id.info);
infoip = (TextView) findViewById(R.id.infoip);
msg = (TextView) findViewById(R.id.msg);
//instantiate custom adapter
MyCustomAdapter adapter = new MyCustomAdapter(list, this);
//handle listview and assign adapter
ListView lView = (ListView)findViewById(R.id.myListView);
lView.setAdapter(adapter);
infoip.setText(getIpAddress());
Thread socketServerThread = new Thread(new SocketServerThread());
socketServerThread.start();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
public void addOrder(String ordername)
{
list.add(ordername);
}
#Override
protected void onDestroy() {
super.onDestroy();
if (serverSocket != null) {
try {
serverSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
#Override
public void onStart() {
super.onStart();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client.connect();
Action viewAction = Action.newAction(
Action.TYPE_VIEW, // TODO: choose an action type.
"Main Page", // TODO: Define a title for the content shown.
// TODO: If you have web page content that matches this app activity's content,
// make sure this auto-generated web page URL is correct.
// Otherwise, set the URL to null.
Uri.parse("http://host/path"),
// TODO: Make sure this auto-generated app deep link URI is correct.
Uri.parse("android-app://com.buzzer.ventern.clientservertrial/http/host/path")
);
AppIndex.AppIndexApi.start(client, viewAction);
}
#Override
public void onStop() {
super.onStop();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
Action viewAction = Action.newAction(
Action.TYPE_VIEW, // TODO: choose an action type.
"Main Page", // TODO: Define a title for the content shown.
// TODO: If you have web page content that matches this app activity's content,
// make sure this auto-generated web page URL is correct.
// Otherwise, set the URL to null.
Uri.parse("http://host/path"),
// TODO: Make sure this auto-generated app deep link URI is correct.
Uri.parse("android-app://com.buzzer.ventern.clientservertrial/http/host/path")
);
AppIndex.AppIndexApi.end(client, viewAction);
client.disconnect();
}
public class SocketServerThread extends Thread {
String ordername;
static final int SocketServerPORT = 8080;
int count = 0;
MainActivity ma= new MainActivity();
#Override
public void run() {
Socket socket = null;
DataInputStream dataInputStream = null;
DataOutputStream dataOutputStream = null;
try {
serverSocket = new ServerSocket(SocketServerPORT);
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
info.setText("I'm waiting here: "
+ serverSocket.getLocalPort());
}
});
while (true) {
socket = serverSocket.accept();
dataInputStream = new DataInputStream(
socket.getInputStream());
dataOutputStream = new DataOutputStream(
socket.getOutputStream());
String messageFromClient = "";
//If no message sent from client, this code will block the program
messageFromClient = dataInputStream.readUTF();
ordername=dataInputStream.readUTF();
ma.addOrder(ordername);
count++;
message += "#" + count + " from " + socket.getInetAddress()
+ ":" + socket.getPort() + "\n"
+ "Msg from client: " + messageFromClient + "\n";
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
msg.setText(message);
}
});
String msgReply = "Hello from server, order #" + count+" has been accepted.";
dataOutputStream.writeUTF(msgReply);
dataOutputStream.flush();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
final String errMsg = e.toString();
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
msg.setText(errMsg);
}
});
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataInputStream != null) {
try {
dataInputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataOutputStream != null) {
try {
dataOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
private String getIpAddress() {
String ip = "";
try {
Enumeration<NetworkInterface> enumNetworkInterfaces = NetworkInterface
.getNetworkInterfaces();
while (enumNetworkInterfaces.hasMoreElements()) {
NetworkInterface networkInterface = enumNetworkInterfaces
.nextElement();
Enumeration<InetAddress> enumInetAddress = networkInterface
.getInetAddresses();
while (enumInetAddress.hasMoreElements()) {
InetAddress inetAddress = enumInetAddress.nextElement();
if (inetAddress.isSiteLocalAddress()) {
ip += "SiteLocalAddress: "
+ inetAddress.getHostAddress() + "\n";
}
}
}
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
ip += "Something Wrong! " + e.toString() + "\n";
}
return ip;
}
}`
The MyCustomAdapter
public class MyCustomAdapter extends BaseAdapter implements ListAdapter {
private ArrayList<String> list = new ArrayList<String>();
private Context context;
public MyCustomAdapter(ArrayList<String> list, Context context) {
this.list = list;
this.context = context;
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int pos) {
return list.get(pos);
}
#Override
public long getItemId(int pos) {
return 0;
//just return 0 if your list items do not have an Id variable.
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.layout_list_item, null);
}
//Handle TextView and display string from your list
TextView listItemText = (TextView)view.findViewById(R.id.list_item_string);
listItemText.setText(list.get(position));
//Handle buttons and add onClickListeners
Button deleteBtn = (Button)view.findViewById(R.id.delete_btn);
deleteBtn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
//send acknowledgement to client
list.remove(position); //or some other task
notifyDataSetChanged();
}
});
return view;
}
}
content_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:autoLink="web"
android:text="Server V1.0"
android:textStyle="bold" />
<TextView
android:id="#+id/info"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/infoip"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<ScrollView
android:layout_width="match_parent"
android:layout_height="255dp" >
<TextView
android:id="#+id/msg"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</ScrollView>
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/myListView"
android:layout_gravity="center_horizontal" />
ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/listView"
android:clickable="true"
android:contextClickable="false" />
</LinearLayout>
and the layout_list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/list_item_string"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_alignParentLeft="true"
android:paddingLeft="8dp"
android:textSize="18sp"
android:textStyle="bold" />
<Button
android:id="#+id/delete_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_marginRight="5dp"
android:text="Okay" />
</RelativeLayout>
I am new to android, and alot of this code is referenced from some android-er posts and some from previous stackoverflow answers. If anyone could tell me why my app crashes when started.
EDIT: Solved the error, but now exception in ASyncTAsk in the client, in doInBackground()
code of the doInBackground() of the client app
protected Void doInBackground(Void... arg0) {
Socket socket = null;
DataOutputStream dataOutputStream = null;
DataInputStream dataInputStream = null;
try {
socket = new Socket(dstAddress, dstPort);
dataOutputStream = new DataOutputStream(socket.getOutputStream());
dataInputStream = new DataInputStream(socket.getInputStream());
item=ma.getStr();
dataOutputStream.writeUTF(item);
dataOutputStream.flush();
response = dataInputStream.readUTF();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
response = "UnknownHostException: " + e.toString();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
response = "IOException: " + e.toString();
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataOutputStream != null) {
try {
dataOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataInputStream != null) {
try {
dataInputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return null;
}`

'service discovery failed' error in bluetooth chat application while trying to connect with a remote device, which is not available at that time

i am building a bluetooth chat application in android platform. everything is going fine but i have slight bug in my application . when i am trying to connect with a remote device which is present in my paired devices list and not available currently as a nearby device, then it throws "service discovery failed" exception and my application gets terminated automatically .
To prevent this automatic termination i have also put the condition like if such a exception occurs then start the "accept thread" again but it is not working.
mainActivity.java source code
package simpleweather.bluetooth_test1;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;
import java.lang.InterruptedException;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.Context;
import android.content.BroadcastReceiver;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.util.Log;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TabHost;
import android.widget.TextView;
import java.util.Set;
import android.widget.Toast;
import java.util.ArrayList;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView;
import android.view.View;
import android.widget.ArrayAdapter;
public class MainActivity extends AppCompatActivity {
private static final int REQUEST_ENABLE_BT = 1;
BluetoothAdapter bluetoothAdapter;
private UUID myUUID;
private String myName;
Button Refresh;
ListView NewDevices;
ArrayList<String> ScanNewList;
ArrayAdapter<String> ScanNewAdapter;
server serverconnection=null;
ArrayList<String> conversation;
ArrayAdapter<String> sessionchat;
ListView MsgList;
ArrayList<String> pairedDeviceArrayList;
ListView listViewPairedDevice;
ArrayAdapter<String> pairedDeviceAdapter;
client clientconnection=null;
communication datatransfer=null;
EditText input;
FloatingActionButton sent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
NewDevices=(ListView)findViewById(R.id.newDevices);
ScanNewList=new ArrayList<String>();
Refresh=(Button)findViewById(R.id.refresh);
ScanNewAdapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,ScanNewList);
NewDevices.setAdapter(ScanNewAdapter);
sent=(FloatingActionButton)findViewById(R.id.send);
input=(EditText)findViewById(R.id.input);
MsgList=(ListView)findViewById(R.id.msglist);
conversation=new ArrayList<String>();
sessionchat = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, conversation);
MsgList.setAdapter(sessionchat);
TabHost tabHost=(TabHost)findViewById(R.id.tabHost);
tabHost.setup();
TabHost.TabSpec tabSpec=tabHost.newTabSpec("paireddevices");
tabSpec.setContent(R.id.pairedDevices);
tabSpec.setIndicator("Paired Devices");
tabHost.addTab(tabSpec);
tabSpec=tabHost.newTabSpec("msgArea");
tabSpec.setContent(R.id.chatArea);
tabSpec.setIndicator("Start Chat");
tabHost.addTab(tabSpec);
tabSpec=tabHost.newTabSpec("newdiscovered_devices");
tabSpec.setContent(R.id.newdevices);
tabSpec.setIndicator("Scan Devices");
tabHost.addTab(tabSpec);
listViewPairedDevice=(ListView)findViewById(R.id.listView);
sent.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
if(datatransfer!=null){
byte[] bytesToSend = input.getText().toString().getBytes();
datatransfer.write(bytesToSend,input.getText().toString());
input.setText("");
}
}});
if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH)){
Toast.makeText(getBaseContext(),"FEATURE_BLUETOOTH NOT support",Toast.LENGTH_SHORT).show();
finish();
return;
}
myUUID = UUID.fromString("ec79da00-853f-11e4-b4a9-0800200c9a66");
myName = myUUID.toString();
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (bluetoothAdapter == null) {
Toast.makeText(getBaseContext(),"Bluetooth is not supported on this hardware platform",Toast.LENGTH_SHORT).show();
finish();
return;
}
if (!bluetoothAdapter.isEnabled()) {
Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
}else{
server_start();
client_start();
}
Refresh.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (bluetoothAdapter.isDiscovering()) {
bluetoothAdapter.cancelDiscovery();
}
bluetoothAdapter.startDiscovery();
}
});
// start discovery for new devices
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND); // registering broadcast reciever for retrieving information of new devices
registerReceiver(mReceiver, filter);
NewDevices.setOnItemClickListener(new OnItemClickListener() { // list of newly scaned devices
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
bluetoothAdapter.cancelDiscovery();
String info = ((TextView) view).getText().toString();
String address = info.substring(info.length() - 17);
BluetoothDevice device = bluetoothAdapter.getRemoteDevice(address);
Toast.makeText(MainActivity.this,"Name: " + device.getName() + "\n" + "Address: " + device.getAddress(), Toast.LENGTH_SHORT).show();
clientconnection = new client(device);
clientconnection.start();
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
// check if the request code is same as what is passed here it is 1
if(requestCode==1) {
Log.d("Shashank","Bluetooth turned on ");
server_start();
client_start();
}
}
private synchronized void server_start() {
if(clientconnection!=null)
{
clientconnection.cancel();
clientconnection=null;
}
if(datatransfer!=null){
datatransfer.cancel();
datatransfer=null;
}
if(serverconnection!=null) {
serverconnection.cancel();
serverconnection = null;
}
serverconnection = new server();
serverconnection.start();
}
#Override
protected void onDestroy() {
super.onDestroy();
if(bluetoothAdapter!=null){
bluetoothAdapter.cancelDiscovery();
}
unregisterReceiver(mReceiver);
if(serverconnection!=null){
serverconnection.cancel();
serverconnection=null;
}
if(clientconnection!=null){
clientconnection.cancel();
clientconnection=null;
}
}
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if(!ScanNewList.contains(device.getName()+"\n"+device.getAddress())) {
ScanNewList.add(device.getName() + "\n" + device.getAddress());
ScanNewAdapter.notifyDataSetChanged();
}
}
}
};
private class server extends Thread {
private BluetoothServerSocket bluetoothServerSocket = null;
public server() {
try {
bluetoothServerSocket = bluetoothAdapter.listenUsingRfcommWithServiceRecord(myName, myUUID);
Toast.makeText(getBaseContext(),"Waiting\n" + "bluetoothServerSocket :\n" + bluetoothServerSocket,Toast.LENGTH_SHORT).show();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
server_start();
}
}
#Override
public void run() {
BluetoothSocket bluetoothSocket = null;
if(bluetoothServerSocket!=null){
try {
bluetoothSocket = bluetoothServerSocket.accept();
BluetoothDevice remoteDevice = bluetoothSocket.getRemoteDevice();
final String strConnected = "Connected:\n" + remoteDevice.getName() + "\n" +remoteDevice.getAddress();
//connected
runOnUiThread(new Runnable(){
#Override
public void run() {
Toast.makeText(getBaseContext(),strConnected,Toast.LENGTH_SHORT).show();
}});
start_communication(bluetoothSocket,remoteDevice.getName());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
final String eMessage = e.getMessage();
runOnUiThread(new Runnable(){
#Override
public void run() {
Toast.makeText(getBaseContext(),"something wrong: \n" + eMessage,Toast.LENGTH_SHORT).show();
}});
server_start();
}
}else{
runOnUiThread(new Runnable(){
#Override
public void run() {
Toast.makeText(getBaseContext(),"bluetoothServerSocket == null",Toast.LENGTH_SHORT).show();
}});
}
}
public void cancel() {
Toast.makeText(getBaseContext(),"close bluetoothServerSocket", Toast.LENGTH_SHORT).show();
try {
bluetoothServerSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private void client_start() {
Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices();
if (pairedDevices.size() > 0) {
findViewById(R.id.listView).setVisibility(View.VISIBLE);
pairedDeviceArrayList = new ArrayList<String>();
pairedDeviceAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, pairedDeviceArrayList);
for (BluetoothDevice device : pairedDevices) {
pairedDeviceArrayList.add(device.getName()+"\n"+device.getAddress());
}
pairedDeviceAdapter.notifyDataSetChanged();
listViewPairedDevice.setAdapter(pairedDeviceAdapter);
listViewPairedDevice.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
bluetoothAdapter.cancelDiscovery();
String info = ((TextView) view).getText().toString();
String address = info.substring(info.length() - 17);
BluetoothDevice device = bluetoothAdapter.getRemoteDevice(address);
Toast.makeText(MainActivity.this,"Name: " + device.getName() + "\n"+ "Address: " + device.getAddress(),Toast.LENGTH_SHORT).show();
clientconnection = new client(device);
clientconnection.start();
}});
}
}
private class client extends Thread {
private BluetoothSocket bluetoothSocket = null;
private final BluetoothDevice bluetoothDevice;
public client(BluetoothDevice device) {
bluetoothDevice = device;
try {
bluetoothSocket = device.createRfcommSocketToServiceRecord(myUUID);
Toast.makeText(getBaseContext(),"bluetoothSocket: \n" + bluetoothSocket,Toast.LENGTH_SHORT).show();
} catch (IOException e) {
// TODO Auto-generated catch block
//e.printStackTrace();
server_start();
}
}
#Override
public void run() {
boolean success = false;
try {
bluetoothSocket.connect();
success = true;
} catch (IOException e) {
e.printStackTrace();
final String eMessage = e.getMessage();
runOnUiThread(new Runnable(){
#Override
public void run() {
Toast.makeText(getBaseContext(),"something wrong bluetoothSocket.connect(): \n" + eMessage,Toast.LENGTH_SHORT).show();
}});
try {
bluetoothSocket.close();
}
catch (IOException e2){
e2.printStackTrace();
server_start();
}
}
if(success){
//connect successful
runOnUiThread(new Runnable(){
#Override
public void run() {
Toast.makeText(getBaseContext(),"connection successfull",Toast.LENGTH_SHORT).show();
}});
start_communication(bluetoothSocket,bluetoothDevice.getName());
}else{
//fail
Toast.makeText(getBaseContext(),"Could not connected with the device!",Toast.LENGTH_SHORT).show();
server_start();
}
}
public void cancel() {
Toast.makeText(getBaseContext(), "Closed bluetoothSocket", Toast.LENGTH_SHORT).show();
try {
bluetoothSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private void start_communication(BluetoothSocket socket,String chater){
datatransfer = new communication(socket,chater);
datatransfer.start();
}
private class communication extends Thread {
private final BluetoothSocket connectedBluetoothSocket;
private final InputStream connectedInputStream;
private final OutputStream connectedOutputStream;
String deviceName;
public communication(BluetoothSocket socket,String chater) {
connectedBluetoothSocket = socket;
deviceName=chater;
InputStream in = null;
OutputStream out = null;
try {
in = socket.getInputStream();
out = socket.getOutputStream();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
connectedInputStream = in;
connectedOutputStream = out;
}
#Override
public void run() {
byte[] buffer = new byte[1024];
int bytes;
while (true) {
try {
bytes = connectedInputStream.read(buffer);
String strReceived = new String(buffer, 0, bytes);
final String msgReceived =strReceived;
runOnUiThread(new Runnable(){
#Override
public void run() {
conversation.add(deviceName+" : "+msgReceived);
sessionchat.notifyDataSetChanged();
}});
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
final String msgConnectionLost = "Connection lost:\n" + e.getMessage();
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getBaseContext(), msgConnectionLost, Toast.LENGTH_SHORT).show();
server_start();
}
});
break;
}
}
}
public void write(byte[] buffer,String sendmsg) {
try {
connectedOutputStream.write(buffer);
conversation.add("Me : "+sendmsg);
sessionchat.notifyDataSetChanged();
} catch (IOException e) {
// TODO Auto-generated catch block
server_start();
}
}
public void cancel() {
try {
connectedBluetoothSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
and this is activity layout file
<?xml version="1.0" encoding="utf-8"?>
<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="simpleweather.bluetooth_test1.MainActivity"
tools:showIn="#layout/activity_main">
<TabHost
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/tabHost"
android:layout_alignParentTop="true"
android:layout_alignRight="#+id/textView2"
android:layout_alignEnd="#+id/textView2">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TabWidget
android:id="#android:id/tabs"
android:layout_width="340dp"
android:layout_height="wrap_content"></TabWidget>
<FrameLayout
android:id="#android:id/tabcontent"
android:layout_width="392dp"
android:layout_height="match_parent">
<RelativeLayout
android:id="#+id/chatArea"
android:layout_width="361dp"
android:layout_height="541dp"
android:weightSum="1">
<ListView
android:layout_width="match_parent"
android:layout_height="380dp"
android:id="#+id/msglist"
android:stackFromBottom="true"
android:transcriptMode="alwaysScroll"
android:layout_weight="0.87"
android:layout_above="#+id/send" />
<EditText
android:layout_width="230dp"
android:layout_height="wrap_content"
android:id="#+id/input"
android:hint="Type Message"
android:layout_marginBottom="41dp"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_toStartOf="#+id/send"
android:layout_toLeftOf="#+id/send"
android:layout_marginRight="0dp" />
<android.support.design.widget.FloatingActionButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#android:drawable/ic_dialog_email"
android:id="#+id/send"
android:layout_gravity="center_horizontal"
android:layout_alignBottom="#+id/input"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_marginRight="20dp" />
</RelativeLayout>
<LinearLayout
android:id="#+id/newdevices"
android:layout_width="355dp"
android:layout_height="516dp"
android:orientation="vertical"
android:weightSum="1">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Refresh Scan"
android:id="#+id/refresh"
android:layout_gravity="center_horizontal"
android:layout_marginTop="10dp" />
<ListView
android:layout_width="match_parent"
android:layout_height="379dp"
android:id="#+id/newDevices"
android:layout_marginTop="30dp"
android:layout_weight="0.47" />
</LinearLayout>
<LinearLayout
android:id="#+id/pairedDevices"
android:layout_width="374dp"
android:layout_height="500dp"
android:orientation="vertical"
android:weightSum="1">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Tap over the Listed Devices to start Connection"
android:id="#+id/textView"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="10dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Paired Devices"
android:id="#+id/textView2"
android:layout_below="#+id/textView"
android:layout_centerHorizontal="true"
android:layout_gravity="center_horizontal" />
<ListView
android:layout_width="350dp"
android:layout_height="450dp"
android:id="#+id/listView"
android:layout_below="#+id/textView2"
android:layout_alignRight="#+id/textView"
android:layout_alignEnd="#+id/textView" />
</LinearLayout>
</FrameLayout>
</LinearLayout>
</TabHost>
</RelativeLayout>
</ScrollView>
i have screenshot showing the bug .
screenshot showing the bug
I am confused why all this happening . I searched for the similar questions but i didn't found the situation like my bug . Please help me .
I meant that if your connection failed with an exception, then the error path is executed.
The code to show the "Toast" in the error path is different from all the other Toast calls. (ie. its probably not called on the UI thread), so that might be the issue.
Or there might be an issue somewhere within the server.start() call.

Why I cannot get a value from android?

In my main.xml I set two EditText to get num1 and num 2, on Buntto to run the add operation
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<EditText
android:id="#+id/num1"
android:layout_width="0dp"
android:layout_height="fill_parent"
android:layout_weight="1"
android:hint="num1"
android:inputType="number" />
<TextView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:gravity="center"
android:padding="5dp"
android:text="+" />
<EditText
android:id="#+id/num2"
android:layout_width="0dp"
android:layout_height="fill_parent"
android:layout_weight="1"
android:hint="num2"
android:inputType="number" />
<TextView
android:id="#+id/result"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:gravity="center"
android:padding="5dp"
android:text="=" />
<TextView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:gravity="center"
android:padding="5dp" />
</LinearLayout>
<Button
android:id="#+id/btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:text="add"
android:textSize="10sp" />
MainActivity.java
public class MainActivity extends Activity {
public static final int UPDATE_TEXT = 1;
private EditText etx1;
private EditText etx2;
private TextView result;
Button getresult;
private double num1;
private double num2;
private double resultnum;
private Handler handler = new Handler() {
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case UPDATE_TEXT:
new Thread(new Runnable() {
public void run() {
// TODO Auto-generated method stub
String url = "http://localhost:8080/test/index.jsp?num1="
+ num1 + "&" + "num2=" + num2;
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
httpClient.execute(httpGet);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
result.setText(new Double(resultnum).toString());
break;
default:
break;
}
};
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
etx1 = (EditText) findViewById(R.id.num1);
etx2 = (EditText) findViewById(R.id.num2);
result = (TextView) findViewById(R.id.result);
getresult = (Button) findViewById(R.id.btn);
getresult.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
num1 = Double.parseDouble(etx1.getText().toString());
num2 = Double.parseDouble(etx2.getText().toString());
resultnum = num1 + num2;
// TODO Auto-generated method stub
new Thread(new Runnable() {
public void run() {
// TODO Auto-generated method stub
Message message = new Message();
message.what = UPDATE_TEXT;
handler.sendMessage(message);
}
}).start();
}
});
}
}
And my index.jsp:
<body>
<h1>Using GET Method to Read Form Data</h1>
<ul>
<li><p>
<b>Num1:</b>
<%=request.getParameter("num1")%>
</p></li>
<li><p>
<b>Num2:</b>
<%=request.getParameter("num2")%>
</p></li>
<li><p>
<b>result:</b>
<%=request.getParameter("num2")+request.getParameter("num1")%>
</p></li>
</ul>
When I navigate to http://localhost:8080/test/ in Chrome I see num1 = null, num2 = null, result = nullnull. Why are the values not properly filled in?
Your server is running on a localhost and so your device cannot connect to the server. Set your server to run on 0.0.0.0 and then in your code, change the url to the IP Address of your computer instead of localhost. To find your IP Address, go to your command prompt and type ipconfig. Then look for your ipv4 address.
Your code doesn't enter the onCLick method and that's why your values are always null. Convert your code to this one:
public class MainActivity extends Activity {
public static final int UPDATE_TEXT = 1;
private EditText etx1;
private EditText etx2;
private TextView result;
Button getresult;
private double num1;
private double num2;
private double resultnum;
private Handler handler = new Handler() {
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case UPDATE_TEXT:
new Thread(new Runnable() {
public void run() {
String url = "http://localhost:8080/test/index.jsp?num1="
+ num1 + "&" + "num2=" + num2;
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
httpClient.execute(httpGet);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
result.setText(new Double(resultnum).toString());
break;
default:
break;
}
};
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
etx1 = (EditText) findViewById(R.id.num1);
etx2 = (EditText) findViewById(R.id.num2);
result = (TextView) findViewById(R.id.result);
getresult = (Button) findViewById(R.id.btn);
View.OnClickListener buttonHandler= new View.OnClickListener() {
public void onClick(View v) {
num1 = Double.parseDouble(etx1.getText().toString());
num2 = Double.parseDouble(etx2.getText().toString());
resultnum = num1 + num2;
new Thread(new Runnable() {
public void run() {
Message message = new Message();
message.what = UPDATE_TEXT;
handler.sendMessage(message);
}
}).start();
}
};
getresult.setOnClickListener(buttonHandler);
}
}
I think this will solve your problem.

Categories