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;
}`
Related
I am creating a simple imageview with an id and trying to start an activity when it is clicked but when i click it in the emulator, the app just crashes and gives me (wait or close the app prompt)
here is my:
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:fillViewport="true"
android:orientation="vertical">
<ImageView
android:id="#+id/about"
android:layout_width="match_parent"
android:layout_height="450dp"
android:background="#color/colorPrimaryDark"
android:src="#drawable/twoth" />
</LinearLayout>
and here is my java code
public class MainUi extends AppCompatActivity {
//Variables Declaration.
private Button btn1, btn2, btn3, btn4;
private ImageView img;
//Called when the activity is first created.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_ui);
//Variables Initialization and OnClick Method
img = (ImageView) findViewById(R.id.about);
img.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
//Start another activity
Intent myIntent = new Intent(MainUi.this, Query.class);
startActivity(myIntent);
}
});
}
}
The 'wait or close' thing leads me to think there's something in Query activity that is doing a lot of work on the main thread.
Try to use an AsyncTask and put all your long running processes in the doInBackground part and later handle the response in the onPostExecute.
I guess it depends a lot of what you are actually doing, but AsyncTask should be a good start.
here is the full code, I added the rest of the code just in case you can handle it from the outer (Query) class and not within Async Class.
public class Query extends AppCompatActivity {
private ArrayList<String[]> BB;
private ArrayList<String[]> AA = new ArrayList<String[]>();
private Socket socket = null;
private ObjectInputStream in = null;
private DataOutputStream out = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_query);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
try {
AA = new AsyncAction().execute().get();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
setTextViews();
}
}
public void setTextViews() {
View linearLayout = findViewById(R.id.info);
for (int y = 0; y < AA.size(); y++) {
// for (int x = 0; x < AA.get(0).length; x++) {}
TextView name = new TextView(this);
name.setText(AA.get(y)[0]);
name.setId(y);
name.setGravity(Gravity.CENTER);
name.setTextSize(30);
name.setPadding(0, 30, 0, 0);
name.setTextColor(this.getResources().getColor(R.color.icons));
name.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, 0));
ProgressBar pb = new ProgressBar(this, null, android.R.attr.progressBarStyleHorizontal);
Drawable drawable = pb.getProgressDrawable();
drawable.setColorFilter(new LightingColorFilter(0xFF000000, this.getResources().getColor(R.color.colorPrimary)));
pb.setProgress(100);
final int finalY = y;
name.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
Bundle b = new Bundle();
b.putStringArray("list", AA.get(finalY));
Intent i = new Intent(Query.this, Info.class);
i.putExtras(b);
startActivity(i);
}
});
((LinearLayout) linearLayout).addView(name);
((LinearLayout) linearLayout).addView(pb);
}
}
private class AsyncAction extends AsyncTask<String, Void, ArrayList> {
protected ArrayList doInBackground(String... args) {
try {
socket = new Socket(port, 8888);
out = new DataOutputStream(socket.getOutputStream());
in = new ObjectInputStream(socket.getInputStream());
// action
out.writeInt(2);
try {
in = new ObjectInputStream(socket.getInputStream());
BB = (ArrayList<String[]>) in.readObject();
in.close();
socket.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (UnknownHostException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
return BB;//returns what you want to pass to the onPostExecute()
}
protected void onPostExecute(ArrayList result) {
AA = result;
}
}
}
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
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.
I've created an app which by clicking on a list Item, downloads an image from the Internet on a button click (also it places the url on to the EditText for user to see what the url is).
Initially I'm setting the ProgressBar and TextView (indicating Loading....) in a hide mode. But as the download starts, I would like to bring both TextView and ProgressBar on to the UI and once the download completes, would like to make both of them invisible.
There is NO error message on the LogCat to post. I believe I'm missing something which is tricky :). Let me know if any additional information is required. Thanks SO in advance.
Below is the XML: for LinearLayout which should be ON/OFF
<LinearLayout
android:id="#+id/loadingSection"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/downloadImage"
android:visibility="gone"
android:orientation="vertical" >
<TextView
android:id="#+id/loadingMessage"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Loading....."
android:gravity="center"
android:textAppearance="?android:attr/textAppearanceSmall" />
<ProgressBar
android:id="#+id/progressBar"
style="?android:attr/progressBarStyleSmall"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:indeterminate="true" />
</LinearLayout>
And below is the Java file:
public class DownloadImages_HandlerMainActivity extends Activity implements OnItemClickListener {
private EditText editText;
private ListView listView;
private TextView textView;
private String[] listOfImages;
private Button downloadImage;
private ProgressBar progressBar;
private LinearLayout loadingSection = null;
private Handler handler;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.downloadimages_main);
editText = (EditText) findViewById(R.id.downloadURL);
textView = (TextView) findViewById(R.id.loadingMessage);
listView = (ListView) findViewById(R.id.urlList);
downloadImage = (Button) findViewById(R.id.downloadImage);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
listOfImages = getResources().getStringArray(R.array.imageURLs);
listView.setOnItemClickListener(this);
handler = new Handler();
}
#Override
public void onItemClick(AdapterView<?> arg0, View view, int position,
long id) {
editText.setText(listOfImages[position]);
}
public void downloadImage(View view) {
String url = editText.getText().toString();
Thread myThread = new Thread(new DownloadImagesThread(url));
myThread.start();
}
public boolean downloadImageUsingThreads(String url) {
boolean successful = false;
URL downloadURL = null;
HttpURLConnection connection = null;
InputStream inputStream = null;
File file = null;
FileOutputStream fileOutputStream = null;
try {
downloadURL = new URL(url);
connection = (HttpURLConnection) downloadURL.openConnection();
inputStream = connection.getInputStream();
file = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES).getAbsolutePath()
+ "/" + Uri.parse(url).getLastPathSegment());
fileOutputStream = new FileOutputStream(file);
int read = -1;
byte[] buffer = new byte[1024];
while ((read = inputStream.read(buffer)) != -1) {
fileOutputStream.write(buffer, 0, read);
//Log.d("BRK0018", " " + read);
successful = true;
}
} catch (MalformedURLException e) {
e.printStackTrace();
Log.d("BRK0018", " " + e);
} catch (IOException e) {
e.printStackTrace();
Log.d("BRK0018", " " + e);
} finally {
// This is the HANDLER INSTANCE in place of thread
handler.post(new Runnable() {
#Override
public void run() {
try {
loadingSection.setVisibility(View.GONE); // Making the ProgressBar INVISIBLE
} catch (Exception e) {
Log.d("BRK0018", " " + e);
}
}
});
if (connection != null) {
connection.disconnect();
}
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
Log.d("BRK0018", " " + e);
}
}
}
return successful;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
private class DownloadImagesThread implements Runnable {
private String url;
public DownloadImagesThread(String url) {
this.url = url;
}
// This is the HANDLER INSTANCE in place of thread
#Override
public void run() {
handler.post(new Runnable() {
#Override
public void run() {
try {
// TODO Auto-generated method stub
loadingSection.setVisibility(View.VISIBLE); // Making the ProgressBar VISIBLE
} catch (Exception e) {
Log.d("BRK0018", " " + e);
}
}
});
downloadImageUsingThreads(url);
}
}
}
The problem here is loadingSection which is null. And since you change its visibility in try/catch block, the app doesn't crash. Initialize the layout in onCreate():
loadingSection = (LinearLayout) findViewById(R.id.loadingSection);
First of all, when you call
handler.post(new Runnable() {
#Override
public void run() {
try {
// TODO Auto-generated method stub
loadingSection.setVisibility(View.VISIBLE);
Thread.sleep(1000);
} catch (Exception e) {
Log.d("BRK0018", " " + e);
}
}
});
Handler.class runs above code in UI thread.
You must not call Thread.sleep(1000) in UI thread.
(but anyway remember that loadingSection.setVisibility(View.VISIBLE); must be called in UI thread)
Fix it. And whether it helps or not write me.
The titles explains, when I try to run my app on my phone eclipse give me an error message about classpath source, please any help
That's my code and it's running perfectly on the AVD
Even when I export the apk file it runs on the android virtual device but when I install it on my phone device the application unfortunaly stops
activity_main.xml
<RelativeLayout 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: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:id="#+id/textView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#+id/button1"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_marginTop="23dp"
android:text="TextView" />
</RelativeLayout>
Manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="application.android.news2"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="9"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="application.android.news2.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
MainActivity.java
public class MainActivity extends Activity {
public void a(){
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet("http://test002.herobo.com/Index2.php");
HttpResponse response = null;
try {
response = client.execute(request);
} catch (ClientProtocolException e3) {
// TODO Auto-generated catch block
e3.printStackTrace();
} catch (IOException e3) {
// TODO Auto-generated catch block
e3.printStackTrace();
}
String html = "";
InputStream in = null;
try {
in = response.getEntity().getContent();
} catch (IllegalStateException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
} catch (IOException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder str = new StringBuilder();
String line = null;
try {
while((line = reader.readLine()) != null)
{
str.append(line);
}
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
html = str.toString();
String newStr = html;
newStr = newStr.replace("<", "");
newStr = newStr.replace("!", "");
newStr = newStr.replace("-", "");
newStr = newStr.replace(":", "");
newStr = newStr.replace("/", "");
newStr = newStr.replace(">", "");
newStr = newStr.replace(".", "");
newStr = newStr.replace("=", "");
String s='"'+"";
newStr = newStr.replace(s, "");
String delStr = "Hosting24 Analytics Code script typetextjavascript
srchttpstatshosting24comcountphpscript End Of Analytics Code";
newStr = newStr.replace(delStr, "");
TextView textView2 = (TextView)findViewById(R.id.textView);
textView2.setText(newStr);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
a();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
You're accessing Network in the Main Thread, which is not allowed. Read this tutorial to learn how to use AsyncTask for this.
My guess is that your AVD is pre Android 3.0, and that your device is Android 3.0 and above, and that you are running into a NetworkOnMainThreadException, since you a() method is called directly from onCreate(), and does network operations.
Try moving your networking code into a background thread or an AsyncTask.
you should not call a() method in MainThread, please follow below code to call a() method.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new LoadDataTask ().execute();
}
private class LoadDataTask extends AsyncTask<Void, Void, String> {
#Override
protected String doInBackground(Void... params) {
try {
return a();
} catch (IOException e) {
e.printStackTrace();
return "";
}
}
#Override
protected void onPostExecute(String result) {
refreshTextView(result);
}
}
public String a() {
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet("http://test002.herobo.com/Index2.php");
HttpResponse response = null;
try {
response = client.execute(request);
} catch (ClientProtocolException e3) {
// TODO Auto-generated catch block
e3.printStackTrace();
} catch (IOException e3) {
// TODO Auto-generated catch block
e3.printStackTrace();
}
String html = "";
InputStream in = null;
try {
in = response.getEntity().getContent();
} catch (IllegalStateException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
} catch (IOException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder str = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
str.append(line);
}
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return str == null ? "" : str.toString();
}
private void refreshTextView(String newStr) {
newStr = newStr.replace("<", "").replace("!", "").replace("-", "")
.replace(":", "").replace("/", "").replace(">", "")
.replace(".", "").replace("=", "");
String s = '"' + "";
newStr = newStr.replace(s, "");
String delStr = "Hosting24 Analytics Code script typetextjavascriptsrchttpstatshosting24comcountphpscript End Of Analytics Code";
newStr = newStr.replace(delStr, "");
TextView textView2 = (TextView) findViewById(R.id.textView);
textView2.setText(newStr);
}