Why I cannot get a value from android? - java

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.

Related

Issue with multiple Volley requests

Whenever I want to perform Volley request based on user input I must press button twice to instead of click the button only one time to get the requested response.
I Used wait() function, but still have the same problem and application corrupted, while I expected the application work normally.
This is what I have reached to until now:
String URL="https://apifootball.com/api/?action=get_countries&APIkey=b4c74bf2fcf3937f783b752649018a42a3b1bde9d5d7c03ff36f61fc06c00c77";
RequestQueue rq= Volley.newRequestQueue(this);
JsonArrayRequest objreq= new JsonArrayRequest(
Request.Method.GET,
URL,
null,
new Response.Listener<JSONArray>()
{
#Override
public void onResponse(JSONArray response) {
try {
Log.e("result:",response.get(0).toString());
JSONObject obj;
for (int count = 0; count < response.length(); count++) {
obj = response.getJSONObject(count);
String name = obj.getString("country_name");
Log.e("Country:",name);
send(name,true);
// Team t=new Team(2,"mki");
//x.insertTeam(t);
//so on
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener(){
#Override
public void onErrorResponse(VolleyError error) {
Log.e("rest response",error.toString());
}
}
);
rq.add(objreq);
btn_send_message.setOnClickListener(new View.OnClickListener() {
ChatModel model;
public void onClick(View v) {
String text = editText.getText().toString();
else if(text.contains("result"))
{
ChatModel model = new ChatModel(text, true); // user send message
list_chat.add(model);
String result="";
String head2Head;
String input[] = text.split(" ");
String[] arr=null ;
DBAdapter dbAdapter=new DBAdapter(x);
try{
result=dbAdapter.getResultfromDB("Bristol City","Reading");
}catch (Exception e)
{
result="error";
}
if(result.equals("error")==true) {
APIAdapter ap = new APIAdapter();
head2Head = ap.getResult("Bristol City", "Reading", "kjkn", getApplicationContext());
finres = head2Head;
Log.e("headto",head2Head);
arr = head2Head.split("\n");
}
model = new ChatModel("First team:"+arr[0]+"\nSecond team:"+arr[1]+"\n"+"Date:"+arr[2], false);
list_chat.add(model);
}
}
Now I do understand your question. The thing that is happening is the data is taking its time to be loaded. So use something like a progress bar and change its visibility inside Response.Listener and Response.ErrorListener. To make this work properly move the line rq.add(objreq); inside onClickListener and before this line change the visibility of the progress bar to visible.
Example
Layout.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:id="#+id/mainParentRel"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:background="#drawable/grad_bg_2"
android:isScrollContainer="true"
android:scrollbars="vertical">
<ScrollView
android:id="#+id/scrollView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:fillViewport="true"
android:scrollbars="vertical">
<!-- You can use any thing here
Put all your previous buttons edittext etc here.
You can replace the scrollview with any layout
Or You can completely remove the scrollview and
directly put your views here. -->
</ScrollView>
<!-- This is the progress bar layout. Always remember to set its visibility to GONE.-->
<RelativeLayout
android:id="#+id/progressRelLayout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:visibility="gone">
<ImageView
android:id="#+id/company_logo_progress"
android:layout_width="200dp"
android:layout_height="200dp"
android:layout_centerHorizontal="true"
android:adjustViewBounds="true"
android:contentDescription="#string/company_logo"
android:scaleType="fitCenter"
android:src="#drawable/company_logo" />
<ProgressBar
android:id="#+id/progressBar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/company_logo_progress"
android:layout_marginTop="5dp"
android:layout_centerHorizontal="true"
android:theme="#style/WhiteAccent"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/progressBar"
android:text="Loading..."
android:textColor="#color/white"
android:textSize="17dp"
android:layout_centerHorizontal="true"/>
</RelativeLayout>
</RelativeLayout>
Example.java
RelativeLayout progressRL;
//Inside onCreate()
progressRL= findViewById(R.id.progressRelLayout);
//Do rest of your stuff
String URL="https://apifootball.com/api/?action=get_countries&APIkey=b4c74bf2fcf3937f783b752649018a42a3b1bde9d5d7c03ff36f61fc06c00c77";
RequestQueue rq= Volley.newRequestQueue(this);
JsonArrayRequest objreq= new JsonArrayRequest(
Request.Method.GET,
URL,
null,
new Response.Listener<JSONArray>()
{
#Override
public void onResponse(JSONArray response) {
progressRL.setVisibility(View.GONE);
try {
Log.e("result:",response.get(0).toString());
JSONObject obj;
for (int count = 0; count < response.length(); count++) {
obj = response.getJSONObject(count);
String name = obj.getString("country_name");
Log.e("Country:",name);
send(name,true);
// Team t=new Team(2,"mki");
//x.insertTeam(t);
//so on
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener(){
#Override
public void onErrorResponse(VolleyError error) {
progressRL.setVisibility(View.GONE);
Log.e("rest response",error.toString());
}
}
);
btn_send_message.setOnClickListener(new View.OnClickListener() {
ChatModel model;
public void onClick(View v) {
rq.add(objreq);
progressRL.setVisibility(View.VISIBLE);
String text = editText.getText().toString();
else if(text.contains("result"))
{
ChatModel model = new ChatModel(text, true); // user send message
list_chat.add(model);
String result="";
String head2Head;
String input[] = text.split(" ");
String[] arr=null ;
DBAdapter dbAdapter=new DBAdapter(x);
try{
result=dbAdapter.getResultfromDB("Bristol City","Reading");
}catch (Exception e)
{
result="error";
}
if(result.equals("error")==true) {
APIAdapter ap = new APIAdapter();
head2Head = ap.getResult("Bristol City", "Reading", "kjkn", getApplicationContext());
finres = head2Head;
Log.e("headto",head2Head);
arr = head2Head.split("\n");
}
model = new ChatModel("First team:"+arr[0]+"\nSecond team:"+arr[1]+"\n"+"Date:"+arr[2], false);
list_chat.add(model);
}
}
After doing this it might cause errors. Just move the things that will change after loading of data inside Response.Listener.

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!

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;
}`

dynamic list view with check box Issue?

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

Can you please help me with this code?

The problem: When I Type a ID and press the button, it will not load the ID's webpage...
"a url" is the website page i'm trying to create, (Hidden for number of reasons)
It should be working, it loads the first site, but when I try to call for the IDs, the WebView does not change... Can someone please help me? -Thanks, JG1
My code:
#Override
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
wv.setWebViewClient(new OurViewClient());
wv.getSettings().setJavaScriptEnabled(true);
try {
String url = "a url";
wv.loadUrl(url);
} catch (Exception e) {
e.printStackTrace();
}
String lid = "0";
//Clicking button changes to the color
}
final EditText idbox = (EditText) findViewById(R.id.editText1);
final Button idbutton = (Button) findViewById(R.id.idbtn);
final WebView wv = (WebView) findViewById(R.id.webView1);
public void onClick(View v) {
idbutton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
String lid = idbox.getText().toString();
if (lid == "1") {
wv.setWebViewClient(new OurViewClient());
try {
String urla = "a url";
wv.loadUrl(urla);
} catch (Exception e) {
e.printStackTrace();
}
}
if (lid == "2") {
wv.setWebViewClient(new OurViewClient());
try {
String urlb = "a url";
wv.loadUrl(urlb);
} catch (Exception e) {
e.printStackTrace();
}
}
if (lid == "3") {
wv.setWebViewClient(new OurViewClient());
try {
String urlc = "a url";
wv.loadUrl(urlc);
} catch (Exception e) {
e.printStackTrace();
}
}
}
});
}
I guess, You had been called the same URL value like ("a url"). If yes, try to load different URLs in the web view.
If not, do the following changes in your code,
Put break points to debug your code where you get EditText value.
String lid = idbox.getText().toString(); //check lid is null or not
Change the if condition like this,
if(lid.equalsIgnoreCase("1"))
{
//task for rendering web page
}
Check your custom view client class.
Never mind, You written onClick() method definition is wrongly!
I confused because,
Have you been adding the onclick(android:onClick="onClick") function for button in xml.
In spite of I did some bit changes in your code,
activity_main.xml:
<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"
tools:context=".MainActivity" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:weightSum="2" >
<EditText
android:id="#+id/urlValue"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="2dp"
android:layout_weight="1.5" />
<Button
android:id="#+id/urlBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="2dp"
android:layout_weight="0.5"
android:text="load"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent" >
<WebView
android:id="#+id/webView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
MainActivity.java:
public class MainActivity extends Activity {
private EditText getUrlValue;
private Button loadUrl;
private WebView webView;
String loadId = "";
String URL_ONE = "a_url";
String URL_TWO = "b_url";
String URL_THREE = "c_url";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getUrlValue = (EditText)findViewById(R.id.urlValue);
loadUrl = (Button)findViewById(R.id.urlBtn);
webView = (WebView)findViewById(R.id.webView);
//initial view for webView
getUrlValue.setText("1"); //here web page will load first url= "a url"
webView.setWebViewClient(new OurViewClient());
//onClick Event for load url button
loadUrl.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
loadId = getUrlValue.getText().toString();
if(loadId.equalsIgnoreCase("1")){
try{
webView.loadUrl(URL_ONE);
}catch (Exception e){
e.printStackTrace();
}
}
else if(loadId.equalsIgnoreCase("2")){
try{
webView.loadUrl(URL_TWO);
}catch (Exception e){
e.printStackTrace();
}
}
else{
try{
webView.loadUrl(URL_THREE);
}catch (Exception e){
e.printStackTrace();
}
}
}
});
}
}
remember to add internet permission in the manifest xml file.

Categories