I am learning java through a video tutorial but I am having a strange problem I create a class named OpenedClass in java and implements two classes. One is for OnClickListener and 2nd is OnCheckChangeListener but when i run the application on emulator it always give me the error for the calling OnClickListener. The code for my java class is:
package com.thenewboston.thenewboston;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;
public class OpenedClass extends Activity implements View.OnClickListener,
OnCheckedChangeListener {
TextView question, test;
Button returnData;
RadioGroup selectionList;
String gotBread;
String setData;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.send);
initialize();
private void initialize() {
// TODO Auto-generated method stub
question = (TextView) findViewById(R.id.tvQuestion);
test = (TextView) findViewById(R.id.tvTest);
returnData = (Button) findViewById(R.id.bResults);
selectionList = (RadioGroup) findViewById(R.id.rgAnswers);
selectionList.setOnCheckedChangeListener(this);
returnData.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent person = new Intent();
Bundle backpack = new Bundle();
backpack.putString("answer", setData);
person.putExtras(backpack);
setResult(RESULT_OK,person);
finish();
}
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
// TODO Auto-generated method stub
switch (checkedId) {
case R.id.rCrazy:
setData = "Probably Right !";
break;
case R.id.rSexy:
setData = "Definitely Right !";
break;
case R.id.rBoth:
setData = "Spot On !";
break;
}
test.setText(setData);
}
}
and this is the output for logcat:
01-05 15:59:54.605: E/AndroidRuntime(313): FATAL EXCEPTION: main
01-05 15:59:54.605: E/AndroidRuntime(313): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.thenewboston.thenewboston/com.thenewboston.thenewboston.OpenedClass}: java.lang.NullPointerException
01-05 15:59:54.605: E/AndroidRuntime(313): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)
01-05 15:59:54.605: E/AndroidRuntime(313): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
01-05 15:59:54.605: E/AndroidRuntime(313): at android.app.ActivityThread.access$1500(ActivityThread.java:117)
01-05 15:59:54.605: E/AndroidRuntime(313): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
01-05 15:59:54.605: E/AndroidRuntime(313): at android.os.Handler.dispatchMessage(Handler.java:99)
01-05 15:59:54.605: E/AndroidRuntime(313): at android.os.Looper.loop(Looper.java:123)
01-05 15:59:54.605: E/AndroidRuntime(313): at android.app.ActivityThread.main(ActivityThread.java:3683)
01-05 15:59:54.605: E/AndroidRuntime(313): at java.lang.reflect.Method.invokeNative(Native Method)
01-05 15:59:54.605: E/AndroidRuntime(313): at java.lang.reflect.Method.invoke(Method.java:507)
01-05 15:59:54.605: E/AndroidRuntime(313): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
01-05 15:59:54.605: E/AndroidRuntime(313): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
01-05 15:59:54.605: E/AndroidRuntime(313): at dalvik.system.NativeStart.main(Native Method)
01-05 15:59:54.605: E/AndroidRuntime(313): Caused by: java.lang.NullPointerException
01-05 15:59:54.605: E/AndroidRuntime(313): at com.thenewboston.thenewboston.OpenedClass.initialize(OpenedClass.java:44)
01-05 15:59:54.605: E/AndroidRuntime(313): at com.thenewboston.thenewboston.OpenedClass.onCreate(OpenedClass.java:25)
01-05 15:59:54.605: E/AndroidRuntime(313): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
01-05 15:59:54.605: E/AndroidRuntime(313): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
01-05 15:59:54.605: E/AndroidRuntime(313): ... 11 more
as you guys can see that it tells me that the error is on line 44 and the line 44 in my code is
returnData.setOnClickListener(this);
I did not understand it at all when I comment this line it will show me the layout when I don't it didn't. Any idea why is this happening ?
From your comments below marcin_j post
<Button android:id="#+id/bReturn" // id is bReturn
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Return" >
</Button>
Change this
returnData = (Button) findViewById(R.id.bResults);
to
returnData = (Button) findViewById(R.id.bReturn);
Related
I am learning android programming and created a basic project using android studio.
My application crashes when I click on the getdata button.
The MainActivity.java:
package com.cs_infotech.newpathshala;
import android.app.Activity;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.support.v4.widget.DrawerLayout;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity
implements NavigationDrawerFragment.NavigationDrawerCallbacks {
/**
* Fragment managing the behaviors, interactions and presentation of the navigation drawer.
*/
private NavigationDrawerFragment mNavigationDrawerFragment;
/**
* Used to store the last screen title. For use in {#link #restoreActionBar()}.
*/
private CharSequence mTitle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mNavigationDrawerFragment = (NavigationDrawerFragment)
getSupportFragmentManager().findFragmentById(R.id.navigation_drawer);
mTitle = getTitle();
// Set up the drawer.
mNavigationDrawerFragment.setUp(
R.id.navigation_drawer,
(DrawerLayout) findViewById(R.id.drawer_layout));
}
#Override
public void onNavigationDrawerItemSelected(int position) {
// update the main content by replacing fragments
Fragment fragment = null;
switch (position) {
case 0:
fragment = new ExampleFragment();
break;
case 1:
fragment = new Example1Fragment();
break;
case 2:
fragment = new Example2Fragment();
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, fragment).commit();
} }
public void onSectionAttached(int number) {
switch (number) {
case 1:
mTitle = "ePathshala";
break;
case 2:
mTitle = "Daily Collection";
break;
case 3:
mTitle = "New Enrolled";
break;
}
}
public void restoreActionBar() {
ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setTitle(mTitle);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
if (!mNavigationDrawerFragment.isDrawerOpen()) {
// Only show items in the action bar relevant to this screen
// if the drawer is not showing. Otherwise, let the drawer
// decide what to show in the action bar.
getMenuInflater().inflate(R.menu.main, menu);
restoreActionBar();
return true;
}
return super.onCreateOptionsMenu(menu);
}
#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();
//noinspection SimplifiableIfStatement
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 {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return 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;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((MainActivity) activity).onSectionAttached(
getArguments().getInt(ARG_SECTION_NUMBER));
}
}
}
test1.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:id="#+id/getdata"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="23dp"
android:text="Get Data" />
<ListView
android:id="#+id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_above="#+id/getdata" />
<TextView
android:id="#+id/vers"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
<TextView
android:id="#+id/name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
<TextView
android:id="#+id/api"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>
Example1Fragment.java:
package com.cs_infotech.newpathshala;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import com.cs_infotech.newpathshala.R;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
public class Example1Fragment extends Fragment {
ListView list;
TextView ver;
TextView name;
TextView api;
Button btngetdata;
ArrayList<HashMap<String, String>> oslist = new ArrayList<HashMap<String, String>>();
//URL to get JSON Array
private static String url = "http://api.learn2crack.com/android/jsonos/";
//JSON Node Names
private static final String TAG_OS = "android";
private static final String TAG_VER = "ver";
private static final String TAG_NAME = "name";
private static final String TAG_API = "api";
JSONArray android = null;
private View v;
public Example1Fragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.test1, container, false);
oslist = new ArrayList<HashMap<String, String>>();
btngetdata = (Button) rootView.findViewById(R.id.getdata);
v=rootView;
btngetdata.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new JSONParse().execute();
//Toast.makeText(getActivity(), "You Clicked at " , Toast.LENGTH_SHORT).show();
}
});
return rootView;
}
private class JSONParse extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
name = (TextView) v.findViewById(R.id.name);
ver = (TextView) v.findViewById(R.id.vers);
api = (TextView) v.findViewById(R.id.api);
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Getting Data ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... args) {
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl("http://api.learn2crack.com/android/jsonos/");
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
pDialog.dismiss();
try {
// Getting JSON Array from URL
android = json.getJSONArray(TAG_OS);
for(int i = 0; i < android.length(); i++){
JSONObject c = android.getJSONObject(i);
// Storing JSON item in a Variable
String ver = c.getString(TAG_VER);
String name = c.getString(TAG_NAME);
String api = c.getString(TAG_API);
// Adding value HashMap key => value
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_VER, ver);
map.put(TAG_NAME, name);
map.put(TAG_API, api);
oslist.add(map);
list=(ListView) v.findViewById(R.id.list);
ListAdapter adapter = new SimpleAdapter(getActivity(), oslist,
R.layout.list_v,
new String[] { TAG_VER,TAG_NAME, TAG_API }, new int[] {
R.id.vers,R.id.name, R.id.api});
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(getActivity(), "You Clicked at " + oslist.get(+position).get("name"), Toast.LENGTH_SHORT).show();
}
});
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
Logcat:
04-10 10:12:52.253 30126-30126/com.cs_infotech.newpathshala D/ActivityThread﹕ handleBindApplication:com.cs_infotech.newpathshala
04-10 10:12:52.343 30126-30126/com.cs_infotech.newpathshala W/ApplicationPackageManager﹕ getCSCPackageItemText()
04-10 10:12:52.343 30126-30126/com.cs_infotech.newpathshala D/DisplayManager﹕ DisplayManager()
04-10 10:12:52.423 30126-30126/com.cs_infotech.newpathshala I/dalvikvm﹕ Could not find method android.view.ViewGroup.onNestedScrollAccepted, referenced from method android.support.v7.internal.widget.ActionBarOverlayLayout.onNestedScrollAccepted
04-10 10:12:52.423 30126-30126/com.cs_infotech.newpathshala W/dalvikvm﹕ VFY: unable to resolve virtual method 11359: Landroid/view/ViewGroup;.onNestedScrollAccepted (Landroid/view/View;Landroid/view/View;I)V
04-10 10:12:52.423 30126-30126/com.cs_infotech.newpathshala D/dalvikvm﹕ VFY: replacing opcode 0x6f at 0x0000
04-10 10:12:52.423 30126-30126/com.cs_infotech.newpathshala I/dalvikvm﹕ Could not find method android.view.ViewGroup.onStopNestedScroll, referenced from method android.support.v7.internal.widget.ActionBarOverlayLayout.onStopNestedScroll
04-10 10:12:52.423 30126-30126/com.cs_infotech.newpathshala W/dalvikvm﹕ VFY: unable to resolve virtual method 11365: Landroid/view/ViewGroup;.onStopNestedScroll (Landroid/view/View;)V
04-10 10:12:52.423 30126-30126/com.cs_infotech.newpathshala D/dalvikvm﹕ VFY: replacing opcode 0x6f at 0x0000
04-10 10:12:52.433 30126-30126/com.cs_infotech.newpathshala I/dalvikvm﹕ Could not find method android.support.v7.internal.widget.ActionBarOverlayLayout.stopNestedScroll, referenced from method android.support.v7.internal.widget.ActionBarOverlayLayout.setHideOnContentScrollEnabled
04-10 10:12:52.433 30126-30126/com.cs_infotech.newpathshala W/dalvikvm﹕ VFY: unable to resolve virtual method 9053: Landroid/support/v7/internal/widget/ActionBarOverlayLayout;.stopNestedScroll ()V
04-10 10:12:52.433 30126-30126/com.cs_infotech.newpathshala D/dalvikvm﹕ VFY: replacing opcode 0x6e at 0x000e
04-10 10:12:52.443 30126-30126/com.cs_infotech.newpathshala I/dalvikvm﹕ Could not find method android.content.res.TypedArray.getChangingConfigurations, referenced from method android.support.v7.internal.widget.TintTypedArray.getChangingConfigurations
04-10 10:12:52.443 30126-30126/com.cs_infotech.newpathshala W/dalvikvm﹕ VFY: unable to resolve virtual method 374: Landroid/content/res/TypedArray;.getChangingConfigurations ()I
04-10 10:12:52.443 30126-30126/com.cs_infotech.newpathshala D/dalvikvm﹕ VFY: replacing opcode 0x6e at 0x0002
04-10 10:12:52.443 30126-30126/com.cs_infotech.newpathshala I/dalvikvm﹕ Could not find method android.content.res.TypedArray.getType, referenced from method android.support.v7.internal.widget.TintTypedArray.getType
04-10 10:12:52.443 30126-30126/com.cs_infotech.newpathshala W/dalvikvm﹕ VFY: unable to resolve virtual method 396: Landroid/content/res/TypedArray;.getType (I)I
04-10 10:12:52.443 30126-30126/com.cs_infotech.newpathshala D/dalvikvm﹕ VFY: replacing opcode 0x6e at 0x0002
04-10 10:12:52.834 30126-30126/com.cs_infotech.newpathshala D/OpenGLRenderer﹕ Enabling debug mode 0
04-10 10:12:52.934 30126-30126/com.cs_infotech.newpathshala I/Timeline﹕ Timeline: Activity_idle id: android.os.BinderProxy#41e049e0 time:9101016
04-10 10:15:04.772 30126-30126/com.cs_infotech.newpathshala I/Timeline﹕ Timeline: Activity_idle id: android.os.BinderProxy#41e049e0 time:9232856
04-10 10:15:11.359 30126-30656/com.cs_infotech.newpathshala W/dalvikvm﹕ threadid=11: thread exiting with uncaught exception (group=0x416c8bc0)
04-10 10:15:11.379 30126-30656/com.cs_infotech.newpathshala E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #1
Process: com.cs_infotech.newpathshala, PID: 30126
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:300)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841)
Caused by: java.lang.SecurityException: Permission denied (missing INTERNET permission?)
at java.net.InetAddress.lookupHostByName(InetAddress.java:418)
at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
at java.net.InetAddress.getAllByName(InetAddress.java:214)
at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
at com.cs_infotech.newpathshala.JSONParser.getJSONFromUrl(JSONParser.java:44)
at com.cs_infotech.newpathshala.Example1Fragment$JSONParse.doInBackground(Example1Fragment.java:80)
at com.cs_infotech.newpathshala.Example1Fragment$JSONParse.doInBackground(Example1Fragment.java:62)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841)
Caused by: libcore.io.GaiException: getaddrinfo failed: EAI_NODATA (No address associated with hostname)
at libcore.io.Posix.getaddrinfo(Native Method)
at libcore.io.ForwardingOs.getaddrinfo(ForwardingOs.java:61)
at java.net.InetAddress.lookupHostByName(InetAddress.java:405)
at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
at java.net.InetAddress.getAllByName(InetAddress.java:214)
at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
at com.cs_infotech.newpathshala.JSONParser.getJSONFromUrl(JSONParser.java:44)
at com.cs_infotech.newpathshala.Example1Fragment$JSONParse.doInBackground(Example1Fragment.java:80)
at com.cs_infotech.newpathshala.Example1Fragment$JSONParse.doInBackground(Example1Fragment.java:62)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841)
Caused by: libcore.io.ErrnoException: getaddrinfo failed: EACCES (Permission denied)
at libcore.io.Posix.getaddrinfo(Native Method)
at libcore.io.ForwardingOs.getaddrinfo(ForwardingOs.java:61)
at java.net.InetAddress.lookupHostByName(InetAddress.java:405)
at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
at java.net.InetAddress.getAllByName(InetAddress.java:214)
at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
at com.cs_infotech.newpathshala.JSONParser.getJSONFromUrl(JSONParser.java:44)
at com.cs_infotech.newpathshala.Example1Fragment$JSONParse.doInBackground(Example1Fragment.java:80)
at com.cs_infotech.newpathshala.Example1Fragment$JSONParse.doInBackground(Example1Fragment.java:62)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841)
04-10 10:15:12.330 30126-30126/com.cs_infotech.newpathshala E/OpenGLRenderer﹕ SFEffectCache:clear(), mSize = 0
04-10 10:15:12.360 30126-30126/com.cs_infotech.newpathshala E/WindowManager﹕ android.view.WindowLeaked: Activity com.cs_infotech.newpathshala.MainActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{41e91890 V.E..... R......D 0,0-471,144} that was originally added here
at android.view.ViewRootImpl.<init>(ViewRootImpl.java:388)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:248)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
at android.app.Dialog.show(Dialog.java:286)
at com.cs_infotech.newpathshala.Example1Fragment$JSONParse.onPreExecute(Example1Fragment.java:74)
at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:587)
at android.os.AsyncTask.execute(AsyncTask.java:535)
at com.cs_infotech.newpathshala.Example1Fragment$1.onClick(Example1Fragment.java:56)
at android.view.View.performClick(View.java:4508)
at android.view.View$PerformClick.run(View.java:18675)
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:5584)
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:1268)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1084)
at dalvik.system.NativeStart.main(Native Method)
04-10 10:15:14.992 30126-30656/com.cs_infotech.newpathshala I/Process﹕ Sending signal. PID: 30126 SIG: 9
How can I resolve this?
I am stuck trying to reading from a .txt file a name and last name into a java application, I have tryed on first method with AssetManager but my application Crash when I enter it.
The second method is with inputstream but I get 3 errors:
Description Resource Path Location Type
ByteArrayOutputStream cannot be resolved to a type MainActivity.java /MyInfo/src/com/example/myinfo line 64 Java Problem
ByteArrayOutputStream cannot be resolved to a type MainActivity.java /MyInfo/src/com/example/myinfo line 64 Java Problem
dummytext cannot be resolved or is not a field MainActivity.java /MyInfo/src/com/example/myinfo line 55 Java Problem
MainActivity.java
package com.example.myinfo;
import java.io.IOException;
import java.io.InputStream;
import android.os.Bundle;
import android.content.res.AssetManager;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/*
TextView name = (TextView) findViewById(R.id.name);
AssetManager assetManager = getAssets();
InputStream input;
try {
input = assetManager.open("info.txt");
int size = input.available();
byte[] buffer = new byte[size];
input.read(buffer);
input.close();
// byte buffer into a string
String text = new String(buffer);
nume.setText(text);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
*/
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
TextView dummytext = (TextView) findViewById(R.id.dummytext);
dummytext.setText(readText());
}
private String readText() {
InputStream inputStream = getResources().openRawResource(R.raw.dummytext);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
int i;
try {
i = inputStream.read();
while(i!=-1){
byteArrayOutputStream.write(i);
i = inputStream.read();
}
inputStream.close();
}catch (IOException e){
e.printStackTrace();
}
return byteArrayOutputStream.toString();
}
#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;
}
}
}
and my XML is this:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.myinfo.MainActivity$PlaceholderFragment" >
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="87dp"
android:text="Adauga Fisier" />
<TextView
android:id="#+id/dummytext"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/nume"
android:layout_below="#+id/nume"
android:layout_marginTop="29dp"
android:text="Prenume"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignRight="#+id/button1"
android:layout_marginRight="14dp"
android:layout_marginTop="65dp"
android:textAppearance="?android:attr/textAppearanceLarge" />
</RelativeLayout>
I don't understand what I did wrong.
When I run the code that is now in Comments I notice that I get in Logcat NullPointerException.
LogCat:
04-07 10:06:11.298: I/dalvikvm(275): Could not find method android.content.pm.PackageManager.getActivityLogo, referenced from method android.support.v7.internal.widget.ActionBarView.<init>
04-07 10:06:11.298: W/dalvikvm(275): VFY: unable to resolve virtual method 318: Landroid/content/pm/PackageManager;.getActivityLogo (Landroid/content/ComponentName;)Landroid/graphics/drawable/Drawable;
04-07 10:06:11.298: D/dalvikvm(275): VFY: replacing opcode 0x6e at 0x008b
04-07 10:06:11.308: I/dalvikvm(275): Could not find method android.content.pm.ApplicationInfo.loadLogo, referenced from method android.support.v7.internal.widget.ActionBarView.<init>
04-07 10:06:11.308: W/dalvikvm(275): VFY: unable to resolve virtual method 314: Landroid/content/pm/ApplicationInfo;.loadLogo (Landroid/content/pm/PackageManager;)Landroid/graphics/drawable/Drawable;
04-07 10:06:11.308: D/dalvikvm(275): VFY: replacing opcode 0x6e at 0x0099
04-07 10:06:11.318: D/dalvikvm(275): VFY: dead code 0x008e-0092 in Landroid/support/v7/internal/widget/ActionBarView;.<init> (Landroid/content/Context;Landroid/util/AttributeSet;)V
04-07 10:06:11.318: D/dalvikvm(275): VFY: dead code 0x009c-00a0 in Landroid/support/v7/internal/widget/ActionBarView;.<init> (Landroid/content/Context;Landroid/util/AttributeSet;)V
04-07 10:06:11.488: D/AndroidRuntime(275): Shutting down VM
04-07 10:06:11.488: W/dalvikvm(275): threadid=1: thread exiting with uncaught exception (group=0x4001d800)
04-07 10:06:11.498: E/AndroidRuntime(275): FATAL EXCEPTION: main
04-07 10:06:11.498: E/AndroidRuntime(275): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.myinfo/com.example.myinfo.MainActivity}: java.lang.NullPointerException
04-07 10:06:11.498: E/AndroidRuntime(275): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
04-07 10:06:11.498: E/AndroidRuntime(275): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
04-07 10:06:11.498: E/AndroidRuntime(275): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
04-07 10:06:11.498: E/AndroidRuntime(275): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
04-07 10:06:11.498: E/AndroidRuntime(275): at android.os.Handler.dispatchMessage(Handler.java:99)
04-07 10:06:11.498: E/AndroidRuntime(275): at android.os.Looper.loop(Looper.java:123)
04-07 10:06:11.498: E/AndroidRuntime(275): at android.app.ActivityThread.main(ActivityThread.java:4627)
04-07 10:06:11.498: E/AndroidRuntime(275): at java.lang.reflect.Method.invokeNative(Native Method)
04-07 10:06:11.498: E/AndroidRuntime(275): at java.lang.reflect.Method.invoke(Method.java:521)
04-07 10:06:11.498: E/AndroidRuntime(275): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
04-07 10:06:11.498: E/AndroidRuntime(275): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
04-07 10:06:11.498: E/AndroidRuntime(275): at dalvik.system.NativeStart.main(Native Method)
04-07 10:06:11.498: E/AndroidRuntime(275): Caused by: java.lang.NullPointerException
04-07 10:06:11.498: E/AndroidRuntime(275): at com.example.myinfo.MainActivity.onCreate(MainActivity.java:42)
04-07 10:06:11.498: E/AndroidRuntime(275): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
04-07 10:06:11.498: E/AndroidRuntime(275): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
04-07 10:06:11.498: E/AndroidRuntime(275): ... 11 more
04-07 10:06:18.688: I/Process(275): Sending signal. PID: 275 SIG: 9
use this code
`InputStream input;
AssetManager assetManager = getAssets();
try {
input = assetManager.open("helloworld.txt");
int size = input.available();
byte[] buffer = new byte[size];
input.read(buffer);
input.close();
// byte buffer into a string
String text = new String(buffer);
dummytext.setText(text);
} catch (IOException e) {
e.printStackTrace();
}
`
This code open an InputStream for the file from assets manager, get size from file content, allocate byte buffer with this size and read file in this buffer, after this create new string from buffer and set this string to your textview
i am trying to navigate between different pages on an Android application, when I run the project it takes me to the Emulator screen but an error message appears:
The following is the code in the .java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Spinner spinner = (Spinner)findViewById(R.id.spinner1);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
this, R.array.MyPictures, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
final Button button = (Button) findViewById(R.id.button02);
button.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
setContentView(R.layout.imageview);
}
});
}
LogCat:
02-27 11:58:41.374: D/AndroidRuntime(313): Shutting down VM
02-27 11:58:41.374: W/dalvikvm(313): threadid=1: thread exiting with uncaught exception (group=0x4001d800)
02-27 11:58:41.454: E/AndroidRuntime(313): FATAL EXCEPTION: main
02-27 11:58:41.454: E/AndroidRuntime(313): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.test/com.example.test.MainActivity}: java.lang.NullPointerException
02-27 11:58:41.454: E/AndroidRuntime(313): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
02-27 11:58:41.454: E/AndroidRuntime(313): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
02-27 11:58:41.454: E/AndroidRuntime(313): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
02-27 11:58:41.454: E/AndroidRuntime(313): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
02-27 11:58:41.454: E/AndroidRuntime(313): at android.os.Handler.dispatchMessage(Handler.java:99)
02-27 11:58:41.454: E/AndroidRuntime(313): at android.os.Looper.loop(Looper.java:123)
02-27 11:58:41.454: E/AndroidRuntime(313): at android.app.ActivityThread.main(ActivityThread.java:4627)
02-27 11:58:41.454: E/AndroidRuntime(313): at java.lang.reflect.Method.invokeNative(Native Method)
02-27 11:58:41.454: E/AndroidRuntime(313): at java.lang.reflect.Method.invoke(Method.java:521)
02-27 11:58:41.454: E/AndroidRuntime(313): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
02-27 11:58:41.454: E/AndroidRuntime(313): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
02-27 11:58:41.454: E/AndroidRuntime(313): at dalvik.system.NativeStart.main(Native Method)
02-27 11:58:41.454: E/AndroidRuntime(313): Caused by: java.lang.NullPointerException
02-27 11:58:41.454: E/AndroidRuntime(313): at com.example.test.MainActivity.onCreate(MainActivity.java:29)
02-27 11:58:41.454: E/AndroidRuntime(313): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
02-27 11:58:41.454: E/AndroidRuntime(313): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
02-27 11:58:41.454: E/AndroidRuntime(313): ... 11 more
is there any mistake am not aware of ???
this is my second project which shows the same Error
thanks
you have
final Button button = (Button) findViewById(R.id.button02);
button.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
setContentView(R.layout.imageview);
}
});
Remove this setContentView(R.layout.imageview); from button click. also remove final and declare spinner and button globally.
So your button click event should something like this.
final Button button = (Button) findViewById(R.id.button02);
button.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
// Do something here
}
});
basically your full activity goes something like this.
Button button;
Spinner spinner;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
spinner = (Spinner)findViewById(R.id.spinner1);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
this, R.array.MyPictures, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
button = (Button) findViewById(R.id.button02);
button.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
Intent mSignup = new Intent(activityOne.this, activityTwo.class);
startActivity(mSignup);
}
});
}
If you are using imageview then set it in onCreate method and then try.
I'm having a problem with two network operations at the same time.
This is the code I'm working on:
public void onClick(View v) {
// TODO onClick
switch(v.getId()){
case R.id.btSelectSong:
openGalleryAudio();
break;
case R.id.btUpload:
if(etSongTitle.getText().toString().isEmpty()){
Toast.makeText(getBaseContext(),
"Select an audio file", Toast.LENGTH_SHORT).show();
} else {
dialog = ProgressDialog.show(AddSong.this, "", "Uploading file...", true);
new Thread(new Runnable() {
public void run() {
runOnUiThread(new Runnable() {
public void run() {
Log.d("Upload", "Uploading started.....");
}
});
uploadFile(uploadFilePath);
}
}).start();
new Thread(new Runnable() {
public void run(){
runOnUiThread(new Runnable() {
public void run() {
Log.d("Insert", "Inserting audio file metadata to server...");
}
});
insertToServer();
}
}).start();
}
break;
}
}
private void insertToServer(){
String strSongFileName = etSongTitle.getText().toString();
String strSongTitleName = etSongTitleName.getText().toString();
String strSongType = spSongType.getSelectedItem().toString();
String strSongUrl =
"http://mlssabio.x10.mx/strings-of-beads/songs/" +
strSongFileName.replaceAll("\\s+","-").replaceAll("\\'", "") + ".mp3";
String strSongLanguage = spSongLanguage.getSelectedItem().toString();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair(TAG_SONGTYPE, strSongType));
params.add(new BasicNameValuePair(TAG_SONGTITLE, strSongTitleName));
params.add(new BasicNameValuePair(TAG_SONGURL, strSongUrl));
params.add(new BasicNameValuePair(TAG_SONGLANGUAGE, strSongLanguage));
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_insert_song,
"POST", params);
// check log cat fro response
Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully created product
Intent i = new Intent(getApplicationContext(), MainActivity.class);
startActivity(i);
// closing this screen
finish();
} else {
// failed to create product
}
} catch (JSONException e) {
e.printStackTrace();
}
}
public int uploadFile(String sourceFileUri) {
String fileName = sourceFileUri;
HttpURLConnection conn = null;
DataOutputStream dos = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
File sourceFile = new File(sourceFileUri);
if (!sourceFile.isFile()) {
dialog.dismiss();
Log.e("uploadFile", "Source File not exist :"
+uploadFilePath);
runOnUiThread(new Runnable() {
public void run() {
Log.d("Test", "Source File not exist :"
+ uploadFilePath);
}
});
return 0;
} else {
try {
// open a URL connection to the Servlet
FileInputStream fileInputStream = new FileInputStream(sourceFile);
URL url = new URL(upLoadServerUri);
// Open a HTTP connection to the URL
conn = (HttpURLConnection) url.openConnection();
conn.setChunkedStreamingMode(maxBufferSize);
conn.setDoInput(true); // Allow Inputs
conn.setDoOutput(true); // Allow Outputs
conn.setUseCaches(false); // Don't use a Cached Copy
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("ENCTYPE", "multipart/form-data");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
conn.setRequestProperty("uploaded_file", fileName);
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name='uploaded_file';filename='"
+ fileName + "'" + lineEnd);
dos.writeBytes(lineEnd);
// create a buffer of maximum size
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// read file and write it into form...
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
// send multipart form data necesssary after file data...
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// Responses from the server (code and message)
serverResponseCode = conn.getResponseCode();
String serverResponseMessage = conn.getResponseMessage();
Log.i("uploadFile", "HTTP Response is : "
+ serverResponseMessage + ": " + serverResponseCode);
if(serverResponseCode == 200){
runOnUiThread(new Runnable() {
public void run() {
String msg = "File Upload Completed.\n\n See uploaded file here : \n\n"
+ uploadFilePath;
Log.d("Test", msg);
Toast.makeText(AddSong.this, "File Upload Complete.",
Toast.LENGTH_SHORT).show();
}
});
}
//close the streams //
fileInputStream.close();
dos.flush();
dos.close();
} // end of try
catch (MalformedURLException ex) {
dialog.dismiss();
ex.printStackTrace();
runOnUiThread(new Runnable() {
public void run() {
Log.d("Test", "MalformedURLException Exception : check script url.");
Toast.makeText(AddSong.this, "MalformedURLException",
Toast.LENGTH_SHORT).show();
}
});
Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
} // end of MalformedURLException ex
catch (Exception e) {
dialog.dismiss();
e.printStackTrace();
runOnUiThread(new Runnable() {
public void run() {
Log.d("Exception", "Got Exception : see logcat ");
Toast.makeText(AddSong.this, "Got Exception : see logcat ",
Toast.LENGTH_SHORT).show();
}
});
Log.e("Upload file to server Exception", "Exception : "
+ e.getMessage(), e);
} // End of catch Exception e
dialog.dismiss();
return serverResponseCode;
} // End else block
}
Basically, my app uploads an audio file to the server and also inserts the file's metadata to the database server. But I'm getting an error. Please see my logcat errors below:
01-05 07:31:56.112: E/WindowManager(32278): Activity com.thesis.string.of.beads.AddSong has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{41879518 V.E..... R.....ID 0,0-200,114} that was originally added here
01-05 07:31:56.112: E/WindowManager(32278): android.view.WindowLeaked: Activity com.thesis.string.of.beads.AddSong has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{41879518 V.E..... R.....ID 0,0-200,114} that was originally added here
01-05 07:31:56.112: E/WindowManager(32278): at android.view.ViewRootImpl.<init>(ViewRootImpl.java:345)
01-05 07:31:56.112: E/WindowManager(32278): at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:239)
01-05 07:31:56.112: E/WindowManager(32278): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
01-05 07:31:56.112: E/WindowManager(32278): at android.app.Dialog.show(Dialog.java:281)
01-05 07:31:56.112: E/WindowManager(32278): at android.app.ProgressDialog.show(ProgressDialog.java:116)
01-05 07:31:56.112: E/WindowManager(32278): at android.app.ProgressDialog.show(ProgressDialog.java:99)
01-05 07:31:56.112: E/WindowManager(32278): at com.thesis.string.of.beads.AddSong.onClick(AddSong.java:158)
01-05 07:31:56.112: E/WindowManager(32278): at android.view.View.performClick(View.java:4240)
01-05 07:31:56.112: E/WindowManager(32278): at android.view.View$PerformClick.run(View.java:17721)
01-05 07:31:56.112: E/WindowManager(32278): at android.os.Handler.handleCallback(Handler.java:730)
01-05 07:31:56.112: E/WindowManager(32278): at android.os.Handler.dispatchMessage(Handler.java:92)
01-05 07:31:56.112: E/WindowManager(32278): at android.os.Looper.loop(Looper.java:137)
01-05 07:31:56.112: E/WindowManager(32278): at android.app.ActivityThread.main(ActivityThread.java:5103)
01-05 07:31:56.112: E/WindowManager(32278): at java.lang.reflect.Method.invokeNative(Native Method)
01-05 07:31:56.112: E/WindowManager(32278): at java.lang.reflect.Method.invoke(Method.java:525)
01-05 07:31:56.112: E/WindowManager(32278): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
01-05 07:31:56.112: E/WindowManager(32278): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
01-05 07:31:56.112: E/WindowManager(32278): at dalvik.system.NativeStart.main(Native Method)
01-05 07:39:22.201: I/uploadFile(32278): HTTP Response is : OK: 200
01-05 07:39:22.221: D/Test(32278): File Upload Completed.
01-05 07:39:22.221: D/Test(32278): See uploaded file here :
01-05 07:39:22.221: D/Test(32278): /storage/sdcard/John Farnham - Please Don't Ask Me.mp3
01-05 07:39:22.290: D/AndroidRuntime(32278): Shutting down VM
01-05 07:39:22.290: W/dalvikvm(32278): threadid=1: thread exiting with uncaught exception (group=0x41465700)
01-05 07:39:22.332: E/AndroidRuntime(32278): FATAL EXCEPTION: main
01-05 07:39:22.332: E/AndroidRuntime(32278): java.lang.IllegalArgumentException: View not attached to window manager
01-05 07:39:22.332: E/AndroidRuntime(32278): at android.view.WindowManagerGlobal.findViewLocked(WindowManagerGlobal.java:406)
01-05 07:39:22.332: E/AndroidRuntime(32278): at android.view.WindowManagerGlobal.removeView(WindowManagerGlobal.java:308)
01-05 07:39:22.332: E/AndroidRuntime(32278): at android.view.WindowManagerImpl.removeView(WindowManagerImpl.java:79)
01-05 07:39:22.332: E/AndroidRuntime(32278): at android.app.Dialog.dismissDialog(Dialog.java:323)
01-05 07:39:22.332: E/AndroidRuntime(32278): at android.app.Dialog$1.run(Dialog.java:119)
01-05 07:39:22.332: E/AndroidRuntime(32278): at android.os.Handler.handleCallback(Handler.java:730)
01-05 07:39:22.332: E/AndroidRuntime(32278): at android.os.Handler.dispatchMessage(Handler.java:92)
01-05 07:39:22.332: E/AndroidRuntime(32278): at android.os.Looper.loop(Looper.java:137)
01-05 07:39:22.332: E/AndroidRuntime(32278): at android.app.ActivityThread.main(ActivityThread.java:5103)
01-05 07:39:22.332: E/AndroidRuntime(32278): at java.lang.reflect.Method.invokeNative(Native Method)
01-05 07:39:22.332: E/AndroidRuntime(32278): at java.lang.reflect.Method.invoke(Method.java:525)
01-05 07:39:22.332: E/AndroidRuntime(32278): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
01-05 07:39:22.332: E/AndroidRuntime(32278): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
01-05 07:39:22.332: E/AndroidRuntime(32278): at dalvik.system.NativeStart.main(Native Method)
01-05 07:31:56.112: E/WindowManager(32278): Activity com.thesis.string.of.beads.AddSong has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{41879518 V.E..... R.....ID 0,0-200,114} that was originally added here
01-05 07:31:56.112: E/WindowManager(32278): android.view.WindowLeaked: Activity com.thesis.string.of.beads.AddSong has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{41879518 V.E..... R.....ID 0,0-200,114} that was originally added here
01-05 07:31:56.112: E/WindowManager(32278): at android.view.ViewRootImpl.<init>(ViewRootImpl.java:345)
01-05 07:31:56.112: E/WindowManager(32278): at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:239)
01-05 07:31:56.112: E/WindowManager(32278): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
01-05 07:31:56.112: E/WindowManager(32278): at android.app.Dialog.show(Dialog.java:281)
01-05 07:31:56.112: E/WindowManager(32278): at android.app.ProgressDialog.show(ProgressDialog.java:116)
01-05 07:31:56.112: E/WindowManager(32278): at android.app.ProgressDialog.show(ProgressDialog.java:99)
01-05 07:31:56.112: E/WindowManager(32278): at com.thesis.string.of.beads.AddSong.onClick(AddSong.java:158)
01-05 07:31:56.112: E/WindowManager(32278): at android.view.View.performClick(View.java:4240)
01-05 07:31:56.112: E/WindowManager(32278): at android.view.View$PerformClick.run(View.java:17721)
01-05 07:31:56.112: E/WindowManager(32278): at android.os.Handler.handleCallback(Handler.java:730)
01-05 07:31:56.112: E/WindowManager(32278): at android.os.Handler.dispatchMessage(Handler.java:92)
01-05 07:31:56.112: E/WindowManager(32278): at android.os.Looper.loop(Looper.java:137)
01-05 07:31:56.112: E/WindowManager(32278): at android.app.ActivityThread.main(ActivityThread.java:5103)
01-05 07:31:56.112: E/WindowManager(32278): at java.lang.reflect.Method.invokeNative(Native Method)
01-05 07:31:56.112: E/WindowManager(32278): at java.lang.reflect.Method.invoke(Method.java:525)
01-05 07:31:56.112: E/WindowManager(32278): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
01-05 07:31:56.112: E/WindowManager(32278): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
01-05 07:31:56.112: E/WindowManager(32278): at dalvik.system.NativeStart.main(Native Method)
01-05 07:39:22.201: I/uploadFile(32278): HTTP Response is : OK: 200
01-05 07:39:22.221: D/Test(32278): File Upload Completed.
01-05 07:39:22.221: D/Test(32278): See uploaded file here :
01-05 07:39:22.221: D/Test(32278): /storage/sdcard/John Farnham - Please Don't Ask Me.mp3
01-05 07:39:22.290: D/AndroidRuntime(32278): Shutting down VM
01-05 07:39:22.290: W/dalvikvm(32278): threadid=1: thread exiting with uncaught exception (group=0x41465700)
01-05 07:39:22.332: E/AndroidRuntime(32278): FATAL EXCEPTION: main
01-05 07:39:22.332: E/AndroidRuntime(32278): java.lang.IllegalArgumentException: View not attached to window manager
01-05 07:39:22.332: E/AndroidRuntime(32278): at android.view.WindowManagerGlobal.findViewLocked(WindowManagerGlobal.java:406)
01-05 07:39:22.332: E/AndroidRuntime(32278): at android.view.WindowManagerGlobal.removeView(WindowManagerGlobal.java:308)
01-05 07:39:22.332: E/AndroidRuntime(32278): at android.view.WindowManagerImpl.removeView(WindowManagerImpl.java:79)
01-05 07:39:22.332: E/AndroidRuntime(32278): at android.app.Dialog.dismissDialog(Dialog.java:323)
01-05 07:39:22.332: E/AndroidRuntime(32278): at android.app.Dialog$1.run(Dialog.java:119)
01-05 07:39:22.332: E/AndroidRuntime(32278): at android.os.Handler.handleCallback(Handler.java:730)
01-05 07:39:22.332: E/AndroidRuntime(32278): at android.os.Handler.dispatchMessage(Handler.java:92)
01-05 07:39:22.332: E/AndroidRuntime(32278): at android.os.Looper.loop(Looper.java:137)
01-05 07:39:22.332: E/AndroidRuntime(32278): at android.app.ActivityThread.main(ActivityThread.java:5103)
01-05 07:39:22.332: E/AndroidRuntime(32278): at java.lang.reflect.Method.invokeNative(Native Method)
01-05 07:39:22.332: E/AndroidRuntime(32278): at java.lang.reflect.Method.invoke(Method.java:525)
01-05 07:39:22.332: E/AndroidRuntime(32278): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
01-05 07:39:22.332: E/AndroidRuntime(32278): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
01-05 07:39:22.332: E/AndroidRuntime(32278): at dalvik.system.NativeStart.main(Native Method)
Note:
the saving of audio file's metadata is working, but the uploading of audio file seems to be not working.
Any ideas? I'm stuck with this problem. I really need your help. Thanks.
From what i see, you make 2 changes to the UI,
you either dismiss the dialog or closing the activity.
I think that you are closing the activity and then trying to do something with the dialog.
therefor you have a leaked window cause there is no activity.
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.