Android Http Request Error [duplicate] - java

This question already has answers here:
How can I fix 'android.os.NetworkOnMainThreadException'?
(66 answers)
Closed 8 years ago.
I had tried many ways to make an http request in android. Logcat keeps giving me errors no matter what i do. I need some help here. I added
uses-permission android:name="android.permission.INTERNET">
to manifest file
I had checked my connection and it says it is connected...
code :
package com.example.gpschat;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.support.v7.app.ActionBarActivity;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity {
String[] messages;
LinearLayout.LayoutParams lp;
TextView tv;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String m = "";
try {
m = excutePost();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.d("gilad", m);
messages = m.split(",");
LinearLayout ll = (LinearLayout) findViewById(R.id.chat);
for (String message : messages)
{
lp = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
tv = new TextView(this);
tv.setId(1);
tv.setTextSize(15);
tv.setText(message);
tv.setLayoutParams(lp);
(ll).addView(tv);
}
}
#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;
}
#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.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public static String excutePost() throws IOException
{
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(new HttpGet("http://laurawharton.com/gps/getM.php"));
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == HttpStatus.SC_OK){
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
String responseString = out.toString();
//..more logic
return responseString;
} else{
//Closes the connection.
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
}
}
error:
09-02 11:43:10.873: W/dalvikvm(1234): threadid=1: thread exiting with uncaught exception (group=0xb3ac8ba8)
09-02 11:43:10.893: E/AndroidRuntime(1234): FATAL EXCEPTION: main
09-02 11:43:10.893: E/AndroidRuntime(1234): Process: com.example.gpschat, PID: 1234
09-02 11:43:10.893: E/AndroidRuntime(1234): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.gpschat/com.example.gpschat.MainActivity}: android.os.NetworkOnMainThreadException
09-02 11:43:10.893: E/AndroidRuntime(1234): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
09-02 11:43:10.893: E/AndroidRuntime(1234): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
09-02 11:43:10.893: E/AndroidRuntime(1234): at android.app.ActivityThread.access$800(ActivityThread.java:135)
09-02 11:43:10.893: E/AndroidRuntime(1234): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
09-02 11:43:10.893: E/AndroidRuntime(1234): at android.os.Handler.dispatchMessage(Handler.java:102)
09-02 11:43:10.893: E/AndroidRuntime(1234): at android.os.Looper.loop(Looper.java:136)
09-02 11:43:10.893: E/AndroidRuntime(1234): at android.app.ActivityThread.main(ActivityThread.java:5017)
09-02 11:43:10.893: E/AndroidRuntime(1234): at java.lang.reflect.Method.invokeNative(Native Method)
09-02 11:43:10.893: E/AndroidRuntime(1234): at java.lang.reflect.Method.invoke(Method.java:515)
09-02 11:43:10.893: E/AndroidRuntime(1234): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
09-02 11:43:10.893: E/AndroidRuntime(1234): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
09-02 11:43:10.893: E/AndroidRuntime(1234): at dalvik.system.NativeStart.main(Native Method)
09-02 11:43:10.893: E/AndroidRuntime(1234): Caused by: android.os.NetworkOnMainThreadException
09-02 11:43:10.893: E/AndroidRuntime(1234): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1145)
09-02 11:43:10.893: E/AndroidRuntime(1234): at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
09-02 11:43:10.893: E/AndroidRuntime(1234): at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
09-02 11:43:10.893: E/AndroidRuntime(1234): at java.net.InetAddress.getAllByName(InetAddress.java:214)
09-02 11:43:10.893: E/AndroidRuntime(1234): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
09-02 11:43:10.893: E/AndroidRuntime(1234): at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
09-02 11:43:10.893: E/AndroidRuntime(1234): at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
09-02 11:43:10.893: E/AndroidRuntime(1234): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
09-02 11:43:10.893: E/AndroidRuntime(1234): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
09-02 11:43:10.893: E/AndroidRuntime(1234): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
09-02 11:43:10.893: E/AndroidRuntime(1234): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
09-02 11:43:10.893: E/AndroidRuntime(1234): at com.example.gpschat.MainActivity.excutePost(MainActivity.java:89)
09-02 11:43:10.893: E/AndroidRuntime(1234): at com.example.gpschat.MainActivity.onCreate(MainActivity.java:44)
09-02 11:43:10.893: E/AndroidRuntime(1234): at android.app.Activity.performCreate(Activity.java:5231)
09-02 11:43:10.893: E/AndroidRuntime(1234): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
09-02 11:43:10.893: E/AndroidRuntime(1234): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
09-02 11:43:10.893: E/AndroidRuntime(1234): ... 11 more
09-02 11:43:16.833: I/Process(1234): Sending signal. PID: 1234 SIG: 9

try with AsyncTask
I was just wanted write short comment, but I'm not able to write a comment. I'm sorry.
AsyncTask will help you.
If you need a tutorial, take a look.
link : AsyncTask Android example

Related

Display random month from a button click on android?

I am trying to create an app that lets the user click a button and it will display a random month. I have created a string array in my strings.xml file. Bellow is my main.java, strings.xml and activity.xml. I try to run the app and it just force closes.
package com.example.datebutton;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.graphics.Color;
public class Main extends Activity
{
Button btn;
#Override
public void onCreate(Bundle b)
{
super.onCreate(b);
setContentView(R.layout.activity_main);
btn = (Button) findViewById(R.id.btn1);
final String[] months = getResources().getStringArray(R.array.Months);
final TextView tv =(TextView)findViewById(R.id.text1);
btn.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
int rand = (int) (Math.random() * 12);
tv.setText(months[rand]);
}
});
}
}
here is my activity.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<Button
android:id="#+id/btn1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="updateMonth"
android:text="#string/app_name" />
<TextView
android:id="#+id/text1"
android:layout_width="68dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center_vertical"
android:text="#array/Months" />
</LinearLayout>
here is my strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">DateButton</string>
<string-array name="Months">
<item>January</item>
<item>Feburary</item>
<item>March</item>
<item>April</item>
<item>May</item>
<item>June</item>
<item>July</item>
<item>August</item>
<item>September</item>
<item>October</item>
<item>November</item>
<item>December</item>
</string-array>
</resources>
I'm still getting errors and the app still says unfortunately your app closed. The logcat is below.
09-11 16:55:17.472: W/Resources(1638): Converting to string: TypedValue{t=0x1/d=0x7f0c0000 a=-1 r=0x7f0c0000}
09-11 16:55:17.512: D/AndroidRuntime(1638): Shutting down VM
09-11 16:55:17.512: W/dalvikvm(1638): threadid=1: thread exiting with uncaught exception (group=0xb3a8fba8)
09-11 16:55:17.532: E/AndroidRuntime(1638): FATAL EXCEPTION: main
09-11 16:55:17.532: E/AndroidRuntime(1638): Process: com.example.datebutton, PID: 1638
09-11 16:55:17.532: E/AndroidRuntime(1638): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.datebutton/com.example.datebutton.Main}: java.lang.ClassCastException: android.widget.TextView cannot be cast to android.widget.Button
09-11 16:55:17.532: E/AndroidRuntime(1638): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
09-11 16:55:17.532: E/AndroidRuntime(1638): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
09-11 16:55:17.532: E/AndroidRuntime(1638): at android.app.ActivityThread.access$800(ActivityThread.java:135)
09-11 16:55:17.532: E/AndroidRuntime(1638): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
09-11 16:55:17.532: E/AndroidRuntime(1638): at android.os.Handler.dispatchMessage(Handler.java:102)
09-11 16:55:17.532: E/AndroidRuntime(1638): at android.os.Looper.loop(Looper.java:136)
09-11 16:55:17.532: E/AndroidRuntime(1638): at android.app.ActivityThread.main(ActivityThread.java:5017)
09-11 16:55:17.532: E/AndroidRuntime(1638): at java.lang.reflect.Method.invokeNative(Native Method)
09-11 16:55:17.532: E/AndroidRuntime(1638): at java.lang.reflect.Method.invoke(Method.java:515)
09-11 16:55:17.532: E/AndroidRuntime(1638): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
09-11 16:55:17.532: E/AndroidRuntime(1638): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
09-11 16:55:17.532: E/AndroidRuntime(1638): at dalvik.system.NativeStart.main(Native Method)
09-11 16:55:17.532: E/AndroidRuntime(1638): Caused by: java.lang.ClassCastException: android.widget.TextView cannot be cast to android.widget.Button
09-11 16:55:17.532: E/AndroidRuntime(1638): at com.example.datebutton.Main.onCreate(Main.java:24)
09-11 16:55:17.532: E/AndroidRuntime(1638): at android.app.Activity.performCreate(Activity.java:5231)
09-11 16:55:17.532: E/AndroidRuntime(1638): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
09-11 16:55:17.532: E/AndroidRuntime(1638): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
09-11 16:55:17.532: E/AndroidRuntime(1638): ... 11 more
You forgot to add the line: setContentView(R.layout.activity); before trying to instantiate your button object btn.
To use layout in you Activity you have to connect them both together. Below is how your code should look like:
#Override
public void onCreate(Bundle b) {
super.onCreate(b);
setContentView(R.layout.activity);
btn = (Button) findViewById(R.id.btn1);
final String[] months = getResources().getStringArray(R.array.Months);
final TextView tv =(TextView)findViewById(R.id.text1);
btn.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
int r, g, b;
int rand = (int) (Math.random() * 12);
tv.setText(months[rand]);
}
});
}

Issue with adding DatePickerDialog to project

I follow this example about adding DatePicker to my app when using Android Studio.
import android.support.v4.app.DialogFragment;
public static class DatePickerFragment extends DialogFragment
implements DatePickerDialog.OnDateSetListener {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current date as the default date in the picker
final Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
// Create a new instance of DatePickerDialog and return it
return new DatePickerDialog(getActivity(), this, year, month, day);
}
public void onDateSet(DatePicker view, int year, int month, int day) {
// Do something with the date chosen by the user
}
}
The problem is that I can not even compile the project. Here is the error:
Error:(6, 42) java: cannot find symbol
symbol: class DialogFragment
Error:(7, 36) java: package DatePickerDialog does not exist
I tried import android.support.v4.app.DialogFragment;, but it does not exist. Also I set my project to API 11 as that is minimum api level for this control. Any ideas?
I got datePicker somehow working but now I have error when opening activity that contains datepicker:
07-16 18:17:36.274 1822-1822/mycalories.com.jalle.mycalories D/AndroidRuntime﹕ Shutting down VM
07-16 18:17:36.274 1822-1822/mycalories.com.jalle.mycalories W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0xa4db2b20)
07-16 18:17:36.274 1822-1822/mycalories.com.jalle.mycalories E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: mycalories.com.jalle.mycalories, PID: 1822
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{mycalories.com.jalle.mycalories/mycalories.com.jalle.mycalories.MealsEditActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2121)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
at android.app.ActivityThread.access$800(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5017)
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:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at android.app.Activity.findViewById(Activity.java:1884)
at mycalories.com.jalle.mycalories.MealsEditActivity.<init>(MealsEditActivity.java:23)
at java.lang.Class.newInstanceImpl(Native Method)
at java.lang.Class.newInstance(Class.java:1208)
at android.app.Instrumentation.newActivity(Instrumentation.java:1061)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2112)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
            at android.app.ActivityThread.access$800(ActivityThread.java:135)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:136)
            at android.app.ActivityThread.main(ActivityThread.java:5017)
            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:779)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
            at dalvik.system.NativeStart.main(Native Method)
and here is the activity
package mycalories.com.jalle.mycalories;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import com.parse.Parse;
import com.parse.ParseUser;
//import android.app.DialogFragment;
public class MealsEditActivity extends FragmentActivity implements mycalories.com.jalle.mycalories.DatePickerFragment.TheListener{
public final EditText txtDate=(EditText) findViewById(R.id.txtDate);
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.meals_edit);
Button btnDate = (Button) findViewById(R.id.btnDate);
btnDate.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Utils.MyToast("btnDate", getApplicationContext());
DialogFragment newFragment = new com.jalle.mycalories.DatePickerFragment();
newFragment.show(getSupportFragmentManager(), "datePicker");
}
}
);
}
public void returnDate(String date) {
// TODO Auto-generated method stub
txtDate.setText(date);
}
}
}
What is wrong with this activity ?
have you add android support library to build.gradle of your application ?
for example :
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:support-v4:+'
}
then try to rebuild it.
For exception :
put
public final EditText txtDate=(EditText) findViewById(R.id.txtDate);
this line below
setContentView(R.layout.meals_edit);

AChartEngine - Charts with data from parse.com won't display

I would like to create applications forming charts based on data from parse.com. I have read some examples and tutorials but still have problem with displaying charts. Below is my code:
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.util.Log;
import com.parse.GetCallback;
import com.parse.ParseException;
import com.parse.ParseObject;
import com.parse.ParseQuery;
import org.achartengine.ChartFactory;
import org.achartengine.GraphicalView;
import org.achartengine.chart.PointStyle;
import org.achartengine.model.XYMultipleSeriesDataset;
import org.achartengine.model.XYSeries;
import org.achartengine.renderer.XYMultipleSeriesRenderer;
import org.achartengine.renderer.XYSeriesRenderer;
import java.util.ArrayList;
public class LineGraph {
public ArrayList<Integer> dataArray;
XYMultipleSeriesDataset dataset;
XYMultipleSeriesRenderer renderer;
public static boolean ClickEnabled = true;
public Intent getIntent(Context context) {
ArrayList<Integer> y = this.dataArray;
XYSeries seriesY = new XYSeries("Y");
for (int i = 0; i < y.size(); i++) {
seriesY.add(i, y.get(i));
}
dataset = new XYMultipleSeriesDataset();
dataset.addSeries(seriesY);
renderer.setPanEnabled(true, false);
renderer.setClickEnabled(ClickEnabled);
renderer.setBackgroundColor(Color.WHITE);
renderer.setApplyBackgroundColor(true);
renderer.setChartTitle("Simple data");
renderer.setAxesColor(Color.BLACK);
XYMultipleSeriesRenderer mRenderer = new XYMultipleSeriesRenderer();
XYSeriesRenderer renderer = new XYSeriesRenderer();
renderer.setColor(Color.RED);
renderer.setPointStyle(PointStyle.DIAMOND);
mRenderer.addSeriesRenderer(renderer);
Intent intent = ChartFactory.getLineChartIntent(context, dataset, mRenderer, "Line Graph Title");
return intent;
}
public void getData() {
ParseQuery<ParseObject> query = ParseQuery.getQuery("Counters_data");
query.getInBackground("lxFzCTeOcl", new GetCallback<ParseObject>() {
public void done(ParseObject parseObject, ParseException e) {
if (e == null) {
String object = parseObject.getString("value");
Integer objectValue = Integer.parseInt(object);
if (dataArray == null) {
dataArray = new ArrayList<Integer>();
dataArray.add(objectValue);
}
} else {
Log.d("score", "Error: " + e.getMessage());
}
}
});
}
}
And there is how I invoke charts:
public void lineGraphHandler(View view) {
LineGraph line = new LineGraph();
line.getData();
Intent lineIntent = line.getIntent(this);
startActivity(lineIntent);
}
And XML part:
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/counters"
android:onClick="lineGraphHandler"
android:text="Charts"
android:id="#+id/charts"/>
There is my logcat:
03-26 08:42:13.096 1229-1229/com.example.tst D/dalvikvm﹕ Late-enabling
CheckJNI 03-26 08:42:13.487 1229-1229/com.example.tst D/libEGL﹕ loaded
/system/lib/egl/libEGL_genymotion.so 03-26 08:42:13.491
1229-1229/com.example.tst D/﹕ HostConnection::get() New Host
Connection established 0xb94f4270, tid 1229 03-26 08:42:13.551
1229-1229/com.example.tst D/libEGL﹕ loaded
/system/lib/egl/libGLESv1_CM_genymotion.so 03-26 08:42:13.551
1229-1229/com.example.tst D/libEGL﹕ loaded
/system/lib/egl/libGLESv2_genymotion.so 03-26 08:42:14.035
1229-1229/com.example.tst W/EGL_genymotion﹕ eglSurfaceAttrib not
implemented 03-26 08:42:14.039 1229-1229/com.example.tst
E/OpenGLRenderer﹕ Getting MAX_TEXTURE_SIZE from GradienCache 03-26
08:42:14.043 1229-1229/com.example.tst E/OpenGLRenderer﹕
MAX_TEXTURE_SIZE: 4096 03-26 08:42:14.055 1229-1229/com.example.tst
E/OpenGLRenderer﹕ Getting MAX_TEXTURE_SIZE from
Caches::initConstraints() 03-26 08:42:14.063 1229-1229/com.example.tst
E/OpenGLRenderer﹕ MAX_TEXTURE_SIZE: 4096 03-26 08:42:14.063
1229-1229/com.example.tst D/OpenGLRenderer﹕ Enabling debug mode 0
03-26 08:42:50.327 1229-1229/com.example.tst D/dalvikvm﹕ GC_FOR_ALLOC
freed 200K, 8% free 2975K/3228K, paused 10ms, total 13ms 03-26
08:42:51.675 1229-1229/com.example.tst D/dalvikvm﹕ GC_FOR_ALLOC freed
431K, 14% free 3056K/3540K, paused 22ms, total 28ms 03-26 08:42:52.043
1229-1229/com.example.tst W/EGL_genymotion﹕ eglSurfaceAttrib not
implemented 03-26 08:42:53.543 1229-1229/com.example.tst
I/Choreographer﹕ Skipped 89 frames! The application may be doing too
much work on its main thread. 03-26 08:43:01.747
1229-1229/com.example.tst D/AndroidRuntime﹕ Shutting down VM 03-26
08:43:01.747 1229-1229/com.example.tst W/dalvikvm﹕ threadid=1: thread
exiting with uncaught exception (group=0xa4d8fb20) 03-26 08:43:01.767
1229-1229/com.example.tst E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.tst, PID: 1229 java.lang.IllegalStateException:
Could not execute method of the activity at
android.view.View$1.onClick(View.java:3823) at
android.view.View.performClick(View.java:4438) at
android.view.View$PerformClick.run(View.java:18422) 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:5017) 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:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595) at
dalvik.system.NativeStart.main(Native Method) Caused by:
java.lang.reflect.InvocationTargetException at
java.lang.reflect.Method.invokeNative(Native Method) at
java.lang.reflect.Method.invoke(Method.java:515) at
android.view.View$1.onClick(View.java:3818) at
android.view.View.performClick(View.java:4438) at
android.view.View$PerformClick.run(View.java:18422) 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:5017)
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:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method) Caused by:
java.lang.NullPointerException at
com.example.tst.LineGraph.getIntent(LineGraph.java:36) at
com.example.tst.MainActivity.lineGraphHandler(MainActivity.java:44)
at java.lang.reflect.Method.invokeNative(Native Method) at
java.lang.reflect.Method.invoke(Method.java:515) at
android.view.View$1.onClick(View.java:3818) at
android.view.View.performClick(View.java:4438) at
android.view.View$PerformClick.run(View.java:18422) 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:5017)
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:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method) 03-26 08:43:04.507
1229-1229/com.example.tst I/Process﹕ Sending signal. PID: 1229 SIG: 9
I don't understand where the problem is. My app starts but crashes immediately when I push "chart" button. Is it data type of problem or because I misunderstand something?
Thank you in advance.
I tried like this but still got crash:
public void done(ParseObject parseObject, ParseException e) {
if (e == null) {
String object = parseObject.getString("value");
Integer objectValue = Integer.parseInt(object);
if (dataArray == null) {
dataArray = new ArrayList<Integer>();
dataArray.add(objectValue);
ArrayList<Integer> y = dataArray;
XYSeries seriesY = new XYSeries("Y");
for (int i = 0; i < y.size(); i++) {
seriesY.add(i, y.get(i));
dataset = new XYMultipleSeriesDataset();
dataset.addSeries(seriesY);
}
}
Your getData() retrieves the data asynchronously. dataArray won't be initialized immediately when you call getIntent().
Wait for the async operation to complete before using the data there. For example, call the code requiring that data from the done() callback.

Android application keep crashing

in the last few days I tried to develop android applications with no success, for some reason my application keep crashing.
the application keeps throwing few exceptions that I didn't succeeded to handle with.
MainActivity.java :
package com.mobIce.digicoin.digitalcoin;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.os.Build;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends ActionBarActivity {
private List<Coin> coins;
public MainActivity(){
coins = new ArrayList<Coin>();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
populateCoins();
populateListView();
}
}
private void populateCoins() {
coins.add(new Coin("Bitcoin", "650", "4", "http://coinmarketcap.com/img/Bitcoin.png"));
coins.add(new Coin("Dogecoin", "100", "400", "http://coinmarketcap.com/img/Bitcoin.png"));
coins.add(new Coin("fafaf", "8065", "400", "http://coinmarketcap.com/img/Bitcoin.png"));
}
private void populateListView() {
ArrayAdapter<Coin> adapter = new MyListAdapter();
ListView list = (ListView) findViewById(R.id.coinsListView);
list.setAdapter(adapter);
}
#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;
}
#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.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
}
private class MyListAdapter extends ArrayAdapter<Coin> {
public MyListAdapter()
{
super(MainActivity.this, R.layout.coin_layout, coins);
}
#Override
public View getView(int position, View convertView, ViewGroup parent){
View itemView = convertView;
if(itemView == null)
itemView = getLayoutInflater().inflate(R.layout.coin_layout, parent, false);
//find the coin to work with.
Coin currentCoin = coins.get(position);
//fill the view
try{
TextView coinName = (TextView) itemView.findViewById(R.id.coinName);
coinName.setText(currentCoin.getName());
TextView coinPrice = (TextView) itemView.findViewById(R.id.coinPrice);
coinPrice.setText(currentCoin.getPrice());
TextView coinPercentage = (TextView) itemView.findViewById(R.id.coinPercentage);
coinPercentage.setText(currentCoin.getPercentage());
}
catch (NullPointerException e){ }
return itemView;
}
}
}
activity_main.xml:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.mobIce.digicoin.digitalcoin.MainActivity"
tools:ignore="MergeRootFrame" />
fragment_main.xml:
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/coinsListView"
android:paddingLeft="30dp" />
</LinearLayout>
coin_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:padding="8dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="coinName"
android:id="#+id/coinName"
android:layout_alignParentTop="true"
android:layout_toRightOf="#+id/coinIcon"
android:layout_marginTop="35dp"
android:layout_marginLeft="20dp" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/coinIcon"
android:maxHeight="80dp"
android:maxWidth="80dp"
android:minHeight="80dp"
android:minWidth="80dp"
android:src="#drawable/dogecoin"
android:longClickable="false"
android:focusable="false"
android:focusableInTouchMode="false"
android:baselineAlignBottom="false"
android:clickable="false"
android:adjustViewBounds="true"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="#+id/coinPrice"
android:layout_marginLeft="35dp"
android:layout_alignTop="#+id/coinIcon"
android:layout_toRightOf="#+id/coinName"
android:layout_marginTop="25dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Medium Text"
android:id="#+id/coinPercentage"
android:layout_below="#+id/coinPrice"
android:layout_alignLeft="#+id/coinPrice"
android:layout_alignStart="#+id/coinPrice" />
</RelativeLayout>
logcat trace:
03-17 08:59:33.977 1107-1107/com.mobIce.digicoin.digitalcoin D/AndroidRuntime﹕ Shutting down VM
03-17 08:59:33.977 1107-1107/com.mobIce.digicoin.digitalcoin W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0xb1a38ba8)
03-17 08:59:33.987 1107-1107/com.mobIce.digicoin.digitalcoin E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.mobIce.digicoin.digitalcoin, PID: 1107
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.mobIce.digicoin.digitalcoin/com.mobIce.digicoin.digitalcoin.MainActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
at android.app.ActivityThread.access$800(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5017)
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:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.mobIce.digicoin.digitalcoin.MainActivity.populateListView(MainActivity.java:47)
at com.mobIce.digicoin.digitalcoin.MainActivity.onCreate(MainActivity.java:36)
at android.app.Activity.performCreate(Activity.java:5231)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
            at android.app.ActivityThread.access$800(ActivityThread.java:135)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:136)
            at android.app.ActivityThread.main(ActivityThread.java:5017)
            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:779)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
            at dalvik.system.NativeStart.main(Native Method)
03-17 09:04:09.857 1149-1149/com.mobIce.digicoin.digitalcoin D/AndroidRuntime﹕ Shutting down VM
03-17 09:04:09.857 1149-1149/com.mobIce.digicoin.digitalcoin W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0xb1a38ba8)
03-17 09:04:09.867 1149-1149/com.mobIce.digicoin.digitalcoin E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.mobIce.digicoin.digitalcoin, PID: 1149
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.mobIce.digicoin.digitalcoin/com.mobIce.digicoin.digitalcoin.MainActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
at android.app.ActivityThread.access$800(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5017)
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:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.mobIce.digicoin.digitalcoin.MainActivity.populateListView(MainActivity.java:50)
at com.mobIce.digicoin.digitalcoin.MainActivity.onCreate(MainActivity.java:39)
at android.app.Activity.performCreate(Activity.java:5231)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
            at android.app.ActivityThread.access$800(ActivityThread.java:135)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:136)
            at android.app.ActivityThread.main(ActivityThread.java:5017)
            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:779)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
            at dalvik.system.NativeStart.main(Native Method)
03-17 09:06:36.697 1192-1192/com.mobIce.digicoin.digitalcoin D/AndroidRuntime﹕ Shutting down VM
03-17 09:06:36.697 1192-1192/com.mobIce.digicoin.digitalcoin W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0xb1a38ba8)
03-17 09:06:36.717 1192-1192/com.mobIce.digicoin.digitalcoin E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.mobIce.digicoin.digitalcoin, PID: 1192
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.mobIce.digicoin.digitalcoin/com.mobIce.digicoin.digitalcoin.MainActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
at android.app.ActivityThread.access$800(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5017)
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:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.mobIce.digicoin.digitalcoin.MainActivity.populateListView(MainActivity.java:50)
at com.mobIce.digicoin.digitalcoin.MainActivity.onCreate(MainActivity.java:39)
at android.app.Activity.performCreate(Activity.java:5231)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
            at android.app.ActivityThread.access$800(ActivityThread.java:135)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:136)
            at android.app.ActivityThread.main(ActivityThread.java:5017)
            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:779)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
            at dalvik.system.NativeStart.main(Native Method)
03-17 09:13:38.647 1239-1239/com.mobIce.digicoin.digitalcoin D/AndroidRuntime﹕ Shutting down VM
03-17 09:13:38.647 1239-1239/com.mobIce.digicoin.digitalcoin W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0xb1a38ba8)
03-17 09:13:38.747 1239-1239/com.mobIce.digicoin.digitalcoin E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.mobIce.digicoin.digitalcoin, PID: 1239
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.mobIce.digicoin.digitalcoin/com.mobIce.digicoin.digitalcoin.MainActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
at android.app.ActivityThread.access$800(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5017)
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:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.mobIce.digicoin.digitalcoin.MainActivity.populateListView(MainActivity.java:50)
at com.mobIce.digicoin.digitalcoin.MainActivity.onCreate(MainActivity.java:37)
at android.app.Activity.performCreate(Activity.java:5231)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
            at android.app.ActivityThread.access$800(ActivityThread.java:135)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:136)
            at android.app.ActivityThread.main(ActivityThread.java:5017)
            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:779)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
            at dalvik.system.NativeStart.main(Native Method)
03-17 09:13:45.127 1239-1239/com.mobIce.digicoin.digitalcoin I/Process﹕ Sending signal. PID: 1239 SIG: 9
03-17 09:19:34.847 1285-1285/com.mobIce.digicoin.digitalcoin D/AndroidRuntime﹕ Shutting down VM
03-17 09:19:34.847 1285-1285/com.mobIce.digicoin.digitalcoin W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0xb1a38ba8)
03-17 09:19:34.857 1285-1285/com.mobIce.digicoin.digitalcoin E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.mobIce.digicoin.digitalcoin, PID: 1285
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.mobIce.digicoin.digitalcoin/com.mobIce.digicoin.digitalcoin.MainActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
at android.app.ActivityThread.access$800(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5017)
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:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.mobIce.digicoin.digitalcoin.MainActivity.populateListView(MainActivity.java:50)
at com.mobIce.digicoin.digitalcoin.MainActivity.onCreate(MainActivity.java:37)
at android.app.Activity.performCreate(Activity.java:5231)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
            at android.app.ActivityThread.access$800(ActivityThread.java:135)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:136)
            at android.app.ActivityThread.main(ActivityThread.java:5017)
            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:779)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
            at dalvik.system.NativeStart.main(Native Method)
03-17 09:20:11.987 1285-1285/com.mobIce.digicoin.digitalcoin I/Process﹕ Sending signal. PID: 1285 SIG: 9
Your coinsListView is in the fragment layout and not in activity layout. You cannot access it with findViewById() in populateListView() called from activity onCreate(). Instead, move the list view population to the fragment's onCreateView() after the inflation, calling findViewById() on the rootView layout you just inflated.

java.lang.IllegalStateException: Could not execute method of the activity, how to solve?

I am building a timetable app independently regarding school. I am now in the testing stage of my app and it just works fine on android version 2.3.6
However when I try to run it on a virtual device it's starts like normal.
However, after hitting a button which should execute the process to login, the apps returns the following errors:
01-05 00:52:23.180: E/AndroidRuntime(858): FATAL EXCEPTION: main
01-05 00:52:23.180: E/AndroidRuntime(858): java.lang.IllegalStateException: Could not execute method of the activity
01-05 00:52:23.180: E/AndroidRuntime(858): at android.view.View$1.onClick(View.java:3597)
01-05 00:52:23.180: E/AndroidRuntime(858): at android.view.View.performClick(View.java:4202)
01-05 00:52:23.180: E/AndroidRuntime(858): at android.view.View$PerformClick.run(View.java:17340)
01-05 00:52:23.180: E/AndroidRuntime(858): at android.os.Handler.handleCallback(Handler.java:725)
01-05 00:52:23.180: E/AndroidRuntime(858): at android.os.Handler.dispatchMessage(Handler.java:92)
01-05 00:52:23.180: E/AndroidRuntime(858): at android.os.Looper.loop(Looper.java:137)
01-05 00:52:23.180: E/AndroidRuntime(858): at android.app.ActivityThread.main(ActivityThread.java:5039)
01-05 00:52:23.180: E/AndroidRuntime(858): at java.lang.reflect.Method.invokeNative(Native Method)
01-05 00:52:23.180: E/AndroidRuntime(858): at java.lang.reflect.Method.invoke(Method.java:511)
01-05 00:52:23.180: E/AndroidRuntime(858): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
01-05 00:52:23.180: E/AndroidRuntime(858): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
01-05 00:52:23.180: E/AndroidRuntime(858): at dalvik.system.NativeStart.main(Native Method)
01-05 00:52:23.180: E/AndroidRuntime(858): Caused by: java.lang.reflect.InvocationTargetException
01-05 00:52:23.180: E/AndroidRuntime(858): at java.lang.reflect.Method.invokeNative(Native Method)
01-05 00:52:23.180: E/AndroidRuntime(858): at java.lang.reflect.Method.invoke(Method.java:511)
01-05 00:52:23.180: E/AndroidRuntime(858): at android.view.View$1.onClick(View.java:3592)
01-05 00:52:23.180: E/AndroidRuntime(858): ... 11 more
01-05 00:52:23.180: E/AndroidRuntime(858): Caused by: android.os.NetworkOnMainThreadException
01-05 00:52:23.180: E/AndroidRuntime(858): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117)
01-05 00:52:23.180: E/AndroidRuntime(858): at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
01-05 00:52:23.180: E/AndroidRuntime(858): at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
01-05 00:52:23.180: E/AndroidRuntime(858): at java.net.InetAddress.getAllByName(InetAddress.java:214)
01-05 00:52:23.180: E/AndroidRuntime(858): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
01-05 00:52:23.180: E/AndroidRuntime(858): at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
01-05 00:52:23.180: E/AndroidRuntime(858): at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
01-05 00:52:23.180: E/AndroidRuntime(858): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
01-05 00:52:23.180: E/AndroidRuntime(858): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
01-05 00:52:23.180: E/AndroidRuntime(858): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
01-05 00:52:23.180: E/AndroidRuntime(858): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
01-05 00:52:23.180: E/AndroidRuntime(858): at com.mattle.timetable.JSONParser.getJSONFromUrl(JSONParser.java:42)
01-05 00:52:23.180: E/AndroidRuntime(858): at com.mattle.timetable.LoginView.doLogin(LoginView.java:129)
01-05 00:52:23.180: E/AndroidRuntime(858): ... 14 more
I use the jsonparser class from this page: http://www.androidhive.info/2012/01/android-json-parsing-tutorial/
My login code looks like this:
package com.mattle.timetable;
import static com.mattle.timetable.MainActivity.PREFS_NAME;
import java.io.BufferedReader;
import java.math.BigInteger;
import java.net.URI;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import com.google.android.gcm.GCMRegistrar;
import com.markupartist.android.widget.ActionBar;
public class LoginView extends Activity {
private JSONParser jsonParser;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_view);
ActionBar actionBar = (ActionBar) findViewById(R.id.actionbar);
// You can also assign the title programmatically by passing a
// CharSequence or resource id.
actionBar.setTitle("Jouw Lesrooster");
}
#Override
public void onBackPressed() {
Intent startMain = new Intent(Intent.ACTION_MAIN);
startMain.addCategory(Intent.CATEGORY_HOME);
startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(startMain);
}
private String getStringResourceByName(String aString)
{
String packageName = "com.mattle.timetable";
int resId = getResources().getIdentifier(aString, "string", packageName);
return getString(resId);
}
private boolean haveNetworkConnection() {
boolean haveConnectedWifi = false;
boolean haveConnectedMobile = false;
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo[] netInfo = cm.getAllNetworkInfo();
for (NetworkInfo ni : netInfo) {
if (ni.getTypeName().equalsIgnoreCase("WIFI"))
if (ni.isConnected())
haveConnectedWifi = true;
if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
if (ni.isConnected())
haveConnectedMobile = true;
}
return haveConnectedWifi || haveConnectedMobile;
}
public String sha1(String s) {
MessageDigest digest = null;
try {
digest = MessageDigest.getInstance("SHA-1");
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
digest.reset();
byte[] data = digest.digest(s.getBytes());
return String.format("%0" + (data.length*2) + "X", new BigInteger(1, data));
}
public void doRegister(View view) {
Intent gotoregister = new Intent(this, Register.class);
startActivity(gotoregister);
}
public void doLogin(View view) throws Exception {
BufferedReader in = null;
try{
if(haveNetworkConnection()) {
EditText getusername = (EditText) findViewById(R.id.username);
String username = getusername.getText().toString();
EditText getpassword = (EditText) findViewById(R.id.password);
String password = sha1(getpassword.getText().toString() + "SOMESALTHERENVM");
HttpClient client = new DefaultHttpClient();
URI website = new URI("SOMEURL");
HttpPost request = new HttpPost();
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("login_username", username));
nameValuePairs.add(new BasicNameValuePair("login_password", password));
jsonParser = new JSONParser();
JSONObject json = jsonParser.getJSONFromUrl("http://jouwlesrooster.nl/api/doLogin/", nameValuePairs);
try {
if (json.getString("success") != null) {
String res = json.getString("success");
if(Integer.parseInt(res) == 1){
//Log.d("MYTAG", "Print this in logcat...");
//Log.d("MYTAG", username + " ddd " + password);
getSharedPreferences("myLoginshit",MODE_PRIVATE)
.edit()
.putString("Username", username)
.putString("Password", password)
.commit();
GCMRegistrar.checkDevice(this);
GCMRegistrar.checkManifest(this);
String regId = GCMRegistrar.getRegistrationId(this);
if (regId.equals("")) {
GCMRegistrar.register(this, "***");
Log.i("test", "ddd");
// Toast.makeText(getApplicationContext(), "", Toast.LENGTH_LONG).show();
} else {
// Toast.makeText(getApplicationContext(), "Already registered", Toast.LENGTH_LONG).show();
// Log.v(TAG, "Already registered");
}
Intent gotomenu = new Intent(this, Menu.class);
startActivity(gotomenu);
}
}
} finally {
}
} else {
}
}finally{
if (in != null) {
try{
in.close();
}catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
How can I solve this annoying error?
Thanks
Mattle
The problem is the doLogin()-method, which performs Network tasks on the UI-thread.
Looking at your StackTrace you can see:
Caused by: android.os.NetworkOnMainThreadException
this is thrown since Android "Ice Cream Sandwich". To get rid of it, put the Network code in an AsyncTask.
See this older question: How to fix android.os.NetworkOnMainThreadException?
It looks like your executing your doLogin() method from the UI-Thread (possibly some onClick method in a button).
You should not do that, because Network access are potentially slow and could freeze the UI. Use the AsyncTask class instead (see http://developer.android.com/reference/android/os/AsyncTask.html)
Its always better practice to have the UI work on UI-Thread and
Non-UI work on Non-UI Thread, but from HoneyComb version of Android
it became a Law and won't allowed any network operation in the UI
thread
In your case doLogin() is a blocking call, which you are calling from UI thread, where as it should be on the Non-UI thread.
To get rid of this use AsyncTask or Thread.

Categories