Java NullPointer loading remote image to android gallery with imageadapter - java

Hello i am trying to load images from a server into a gallery but always keep giving me this error:
04-28 00:54:47.596: W/dalvikvm(715): threadid=1: thread exiting with uncaught exception (group=0x4001d800)
04-28 00:54:47.608: E/AndroidRuntime(715): FATAL EXCEPTION: main
04-28 00:54:47.608: E/AndroidRuntime(715): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.plateamobile/com.plateamobile.ProdDetails}: java.lang.NullPointerException
04-28 00:54:47.608: E/AndroidRuntime(715): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
04-28 00:54:47.608: E/AndroidRuntime(715): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
04-28 00:54:47.608: E/AndroidRuntime(715): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
04-28 00:54:47.608: E/AndroidRuntime(715): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
04-28 00:54:47.608: E/AndroidRuntime(715): at android.os.Handler.dispatchMessage(Handler.java:99)
04-28 00:54:47.608: E/AndroidRuntime(715): at android.os.Looper.loop(Looper.java:123)
04-28 00:54:47.608: E/AndroidRuntime(715): at android.app.ActivityThread.main(ActivityThread.java:4627)
04-28 00:54:47.608: E/AndroidRuntime(715): at java.lang.reflect.Method.invokeNative(Native Method)
04-28 00:54:47.608: E/AndroidRuntime(715): at java.lang.reflect.Method.invoke(Method.java:521)
04-28 00:54:47.608: E/AndroidRuntime(715): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
04-28 00:54:47.608: E/AndroidRuntime(715): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
04-28 00:54:47.608: E/AndroidRuntime(715): at dalvik.system.NativeStart.main(Native Method)
04-28 00:54:47.608: E/AndroidRuntime(715): Caused by: java.lang.NullPointerException
04-28 00:54:47.608: E/AndroidRuntime(715): at com.plateamobile.ProdDetails.set_info(ProdDetails.java:138)
04-28 00:54:47.608: E/AndroidRuntime(715): at com.plateamobile.ProdDetails.onCreate(ProdDetails.java:49)
04-28 00:54:47.608: E/AndroidRuntime(715): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
04-28 00:54:47.608: E/AndroidRuntime(715): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
04-28 00:54:47.608: E/AndroidRuntime(715): ... 11 more
This is my code:
package com.plateamobile;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.PropertyInfo;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import android.widget.Gallery.LayoutParams;
public class ProdDetails extends Activity {
private ImageSwitcher mSwitcher;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.prod_details);
Bundle extras = getIntent().getExtras();
((TextView)findViewById(R.id.prod_name)).setText(extras.getString("name"));
((TextView)findViewById(R.id.price_prod)).setText(new general().formatNumb(extras.getString("price")));
set_info();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.prod_details, menu);
return true;
}
public void set_info(){
ObjConexion object = new ObjConexion();
SoapObject request = new SoapObject(object.NameSpace(), "getProdinfo");
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
Bundle extras = getIntent().getExtras();
PropertyInfo idPro =new PropertyInfo();
idPro.setName("id");
idPro.setValue(extras.getString("id"));
idPro.setType(String.class);
request.addProperty(idPro);
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(object.Url());
androidHttpTransport.debug = true;
try {
androidHttpTransport.call("getProdinfo", envelope);
List<SoapPrimitive> response = (List<SoapPrimitive>) envelope.getResponse();
((TextView)findViewById(R.id.commerce)).setText(response.get(0).toString());
((TextView)findViewById(R.id.description)).setContentDescription(response.get(1).toString());
}catch (Exception e) {
e.printStackTrace();
Toast.makeText(this,e.getMessage().toString(),Toast.LENGTH_LONG).show();
}
request = new SoapObject(object.NameSpace(), "getProdImg");
envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
idPro =new PropertyInfo();
idPro.setName("id");
idPro.setValue(extras.getString("id"));
idPro.setType(Integer.class);
request.addProperty(idPro);
envelope.setOutputSoapObject(request);
androidHttpTransport = new HttpTransportSE(object.Url());
androidHttpTransport.debug = true;
ArrayList<SoapObject> imagesList = new ArrayList<SoapObject>();
try {
androidHttpTransport.call("getProdImg", envelope);
List<SoapObject> response = (List<SoapObject>) envelope.getResponse();
for (int cont=0; cont<response.size() ;cont++){
SoapObject responseChild = (SoapObject) response.get(cont);
imagesList.add(responseChild);
}
}catch (Exception e) {
e.printStackTrace();
if (e.getMessage() == null){
Toast.makeText(this,"Error en la conexion",Toast.LENGTH_LONG).show();
}else{
Toast.makeText(this,e.getMessage().toString(),Toast.LENGTH_LONG).show();
}
}
Gallery _gallery_ = (Gallery) findViewById(R.id.images_prod);
if (imagesList!=null){
_gallery_.setAdapter(new ImageAdapter(getApplicationContext(), imagesList));
}else{
Log.e("DEBUGTAG", "Remtoe Image Exception");
}
}
public void goBack(View v){
Intent intent = new Intent(ProdDetails.this, main_win.class);
startActivity(intent);
}
public class ImageAdapter extends BaseAdapter {
/** The parent context */
private Context myContext;
/** URL-Strings to some remote images. */
private ArrayList<SoapObject> pckg_data;
/** Simple Constructor saving the 'parent' context. */
public ImageAdapter(Context c, ArrayList<SoapObject> data) {
this.myContext = c;
this.pckg_data = data;
}
/** Returns the amount of images we have defined. */
public int getCount() { return this.pckg_data.size(); }
/* Use the array-Positions as unique IDs */
public Object getItem(int position) { return position; }
public long getItemId(int position) { return position; }
/** Returns a new ImageView to
* be displayed, depending on
* the position passed. */
public View getView(int position, View convertView, ViewGroup parent) {
ImageView i = new ImageView(this.myContext);
try {
/* Open a new URL and get the InputStream to load data from it. */
URL aURL = new URL(pckg_data.get(position).getPropertyAsString(1));
URLConnection conn = aURL.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
/* Buffered is always good for a performance plus. */
BufferedInputStream bis = new BufferedInputStream(is);
/* Decode url-data to a bitmap. */
Bitmap bm = BitmapFactory.decodeStream(bis);
bis.close();
is.close();
/* Apply the Bitmap to the ImageView that will be returned. */
i.setImageBitmap(bm);
} catch (IOException e) {
Log.e("DEBUGTAG", "Remtoe Image Exception", e);
}
/* Image should be scaled as width/height are set. */
i.setScaleType(ImageView.ScaleType.FIT_CENTER);
/* Set the Width/Height of the ImageView. */
i.setLayoutParams(new Gallery.LayoutParams(150, 150));
return i;
}
/** Returns the size (0.0f to 1.0f) of the views
* depending on the 'offset' to the center. */
public float getScale(boolean focused, int offset) {
/* Formula: 1 / (2 ^ offset) */
return Math.max(0, 1.0f / (float)Math.pow(2, Math.abs(offset)));
}
}
}

The first time your app is created there is no intent calling it. So Bundle extras = getIntent().getExtras(); causes the NullPointerException.
Enclose the statement in a try block.
try
{
Bundle extras = getIntent().getExtras();
}
catch(Exception E){
//do nothing
}
But this isn't the right way to do it.
If this activity is going to be called again, I suggest you use onNewIntent() method and make this activity singleTop.
http://developer.android.com/reference/android/app/Activity.html
http://developer.android.com/guide/topics/manifest/activity-element.html

Related

Missing file through getAssets

I have a problem connected with reading a file in Java Application. Please help me as I'm trying to do it for four days and my CS teacher is not into Android Apps. Also any of the tutorials read does not help me.
I have a following app:
package com.bachosz.billionaires;
import android.support.v7.app.ActionBarActivity;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.StringTokenizer;
import android.content.ContextWrapper;
import android.content.res.AssetFileDescriptor;
import android.content.res.AssetManager;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivityBillionaires extends ActionBarActivity {
private int currentQuestion;
private String [] answers;
private Button answerButton;
private Button questionButton;
private TextView questionView;
private TextView answerView;
private EditText answerText;
private Question [] questions;
private Button buttonA;
private Button buttonB;
private Button buttonC;
private Button buttonD;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_activity_billionaires);
try {
init();
} catch (IOException e) {
e.printStackTrace();
}
}
public void init() throws IOException
{
questions = new Question[2];
currentQuestion = 0;
InputStream inputStream = getResources().openRawResource(R.raw.questionstable);
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line = null;
String content,a,b,c,d,correct;
int id, x = 0;
StringTokenizer st = null;
while ((line=reader.readLine()) != null)
{
st= new StringTokenizer(line, ",");
id = Integer.parseInt(st.nextToken());
content = st.nextToken();
a = st.nextToken();
b = st.nextToken();
c = st.nextToken();
d = st.nextToken();
correct = st.nextToken();
questions[x] = new Question(id, content, a, b, c, d, correct);
x++;
}
reader.close();
answerButton = (Button)findViewById(R.id.AnswerButton);
questionButton = (Button)findViewById(R.id.QuestionButton);
questionView = (TextView)findViewById(R.id.QuestionTextView);
answerView = (TextView) findViewById(R.id.AnswerTextView);
answerText = (EditText) findViewById(R.id.AnswerText);
buttonA = (Button)findViewById(R.id.buttonA);
buttonB = (Button)findViewById(R.id.buttonB);
buttonC = (Button)findViewById(R.id.buttonC);
buttonD = (Button)findViewById(R.id.buttonD);
answerButton.setOnClickListener(new OnClickListener()
{
public void onClick(View v) {
checkAnswer();
}});
questionButton.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
showQuestion();
}});
}
public void showQuestion()
{
// if(currentQuestion == questions.length)
// currentQuestion =0;
questionView.setText(questions[0].toString());
answerView.setText("");
answerText.setText("");
currentQuestion++;
}
public boolean isCorrect(String answer)
{
return (answer.equalsIgnoreCase(questions[currentQuestion].getCorrect()));
}
public void checkRight()
{
// String right
}
public void checkAnswer()
{
String answer = questions[currentQuestion].getCorrect();
if(isCorrect(answer))
answerView.setText("You're right!");
else
answerView.setText("Sorry, the correct answer is "+answers[currentQuestion]);
}
#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_activity_billionaires, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
It is taken from Java application I was writing previously (that is why so many comments). How I can access the fileName in Android App? I was trying InputStream, get Assets, etc. but It does not work or I am doing it improperly. Currently it is throwing NullPointerException.
LOG CAT:
10-09 13:38:37.663: E/Trace(921): error opening trace file: No such file or directory (2)
10-09 13:38:39.354: D/AndroidRuntime(921): Shutting down VM
10-09 13:38:39.354: W/dalvikvm(921): threadid=1: thread exiting with uncaught exception (group=0x40a13300)
10-09 13:38:39.384: E/AndroidRuntime(921): FATAL EXCEPTION: main
10-09 13:38:39.384: E/AndroidRuntime(921): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.bachosz.billionaires/com.bachosz.billionaires.MainActivityBillionaires}: java.lang.NullPointerException
10-09 13:38:39.384: E/AndroidRuntime(921): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059)
10-09 13:38:39.384: E/AndroidRuntime(921): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
10-09 13:38:39.384: E/AndroidRuntime(921): at android.app.ActivityThread.access$600(ActivityThread.java:130)
10-09 13:38:39.384: E/AndroidRuntime(921): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
10-09 13:38:39.384: E/AndroidRuntime(921): at android.os.Handler.dispatchMessage(Handler.java:99)
10-09 13:38:39.384: E/AndroidRuntime(921): at android.os.Looper.loop(Looper.java:137)
10-09 13:38:39.384: E/AndroidRuntime(921): at android.app.ActivityThread.main(ActivityThread.java:4745)
10-09 13:38:39.384: E/AndroidRuntime(921): at java.lang.reflect.Method.invokeNative(Native Method)
10-09 13:38:39.384: E/AndroidRuntime(921): at java.lang.reflect.Method.invoke(Method.java:511)
10-09 13:38:39.384: E/AndroidRuntime(921): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
10-09 13:38:39.384: E/AndroidRuntime(921): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
10-09 13:38:39.384: E/AndroidRuntime(921): at dalvik.system.NativeStart.main(Native Method)
10-09 13:38:39.384: E/AndroidRuntime(921): Caused by: java.lang.NullPointerException
10-09 13:38:39.384: E/AndroidRuntime(921): at com.bachosz.billionaires.MainActivityBillionaires.readFile(MainActivityBillionaires.java:111)
10-09 13:38:39.384: E/AndroidRuntime(921): at com.bachosz.billionaires.MainActivityBillionaires.init(MainActivityBillionaires.java:140)
10-09 13:38:39.384: E/AndroidRuntime(921): at com.bachosz.billionaires.MainActivityBillionaires.onCreate(MainActivityBillionaires.java:70)
10-09 13:38:39.384: E/AndroidRuntime(921): at android.app.Activity.performCreate(Activity.java:5008)
10-09 13:38:39.384: E/AndroidRuntime(921): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
10-09 13:38:39.384: E/AndroidRuntime(921): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)
10-09 13:38:39.384: E/AndroidRuntime(921): ... 11 more
The error says you're getting a NPE (Null Pointer Exception) at com.bachosz.billionaires.MainActivityBillionaires. You need to look at the code section that you use to call that activity. (it is not in your code above - or else we don't know which line with the given information)
Another thing you have to make sure is that you have the appropriate context.
AssetManager assetManage = appContext.getAssets();
String[] filelist = assetManage.list("");
First you should clean up your code, at least to show it here where we don't know what are you doing.
It's easier to understand.
Why are you using assets? In Android the most common way to access resources is the .../res/raw folder.
It makes a reference of the file in the autogenerated R.class so you can access it anywhere.
Make sure your filename is lowercase and has no spaces. If you haven't raw folder under res, create it manually.
Try this:
InputStream inputStream = getResources().openRawResource(R.raw.YOURFILE);
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line = reader.readLine();
while (line != null)
{
// Read file.
}
Firstly: copy YOURFILE to assets folder.
Then, AssetManager assetManage = getAssets();
Then,
InputStream myInput = null;
try {
myInput = assetManager.open("YOURFILE");
} catch (IOException e1) {
e1.printStackTrace();
}
And finally BufferedReader reader = new BufferedReader(new InputStreamReader(myInput));
follow the above code step by step.

Structure and sending two arrays to the same receiving function

Good morning,
I'm trying to send two arrays (returned from getValuesGraph(doc) and getValuesFooter(doc) respectively) to the same function (OnPostExecute), I'm newbie at Java and Android and I don't now if the app code structure It's correct. So my apologies for the "disaster".
LogCat says:
02-21 00:07:25.852: W/dalvikvm(3282): threadid=1: thread exiting with uncaught exception (group=0x40a71930)
02-21 00:07:25.862: E/AndroidRuntime(3282): FATAL EXCEPTION: main
02-21 00:07:25.862: E/AndroidRuntime(3282): java.lang.NullPointerException
02-21 00:07:25.862: E/AndroidRuntime(3282): at com.example.kwhora1.MainActivity$BackGroundTask.onPostExecute(MainActivity.java:159)
02-21 00:07:25.862: E/AndroidRuntime(3282): at com.example.kwhora1.MainActivity$BackGroundTask.onPostExecute(MainActivity.java:1)
02-21 00:07:25.862: E/AndroidRuntime(3282): at android.os.AsyncTask.finish(AsyncTask.java:631)
02-21 00:07:25.862: E/AndroidRuntime(3282): at android.os.AsyncTask.access$600(AsyncTask.java:177)
02-21 00:07:25.862: E/AndroidRuntime(3282): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
02-21 00:07:25.862: E/AndroidRuntime(3282): at android.os.Handler.dispatchMessage(Handler.java:99)
02-21 00:07:25.862: E/AndroidRuntime(3282): at android.os.Looper.loop(Looper.java:137)
02-21 00:07:25.862: E/AndroidRuntime(3282): at android.app.ActivityThread.main(ActivityThread.java:5041)
02-21 00:07:25.862: E/AndroidRuntime(3282): at java.lang.reflect.Method.invokeNative(Native Method)
02-21 00:07:25.862: E/AndroidRuntime(3282): at java.lang.reflect.Method.invoke(Method.java:511)
02-21 00:07:25.862: E/AndroidRuntime(3282): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
02-21 00:07:25.862: E/AndroidRuntime(3282): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
02-21 00:07:25.862: E/AndroidRuntime(3282): at dalvik.system.NativeStart.main(Native Method)
Here's the code:
package com.example.kwhora1;
import java.io.IOException;
import java.net.URL;
import java.util.Arrays;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.widget.TextView;
public class MainActivity extends Activity {
private TextView tvmax, tvmid, tvmin, tvactualval;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvmax=(TextView)findViewById(R.id.tvmaximo);
tvmid=(TextView)findViewById(R.id.tvmedio);
tvmin=(TextView)findViewById(R.id.tvminimo);
new BackGroundTask().execute();
}
#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;
}
class BackGroundTask extends AsyncTask<Void, Void, String[]> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
public String[] getValuesGraph(Document doc) {
int cont=24,var=7;
String bar[] = new String[cont];
/*
* Getting elements from the graphic in an array from 0-23. 0 it's 1:00am, 23 it's 00:00am
*/
for (cont=0; cont < 24; cont++){
String onMouseOver = doc.select("a").get(var+cont).attr("onMouseOver");
bar[cont] = onMouseOver.split("'")[9];
}
return bar;
}
public String[] getValuesFooter(Document doc) {
String values[] = new String[7];
/*
* Getting elements from the graphic footer
*/
Elements elements = doc.select("td.cabeceraRutaTexto");
elements.size(); // 6
/* Getting text from table */
values[0] = elements.get(0).text(); // TITLE
values[1] = elements.get(1).text(); // TEXT MAX VALUE
values[2] = elements.get(2).text(); // TEXT MIDDLE VALUE
values[3] = elements.get(3).text(); // TEXTO MIN VALUE
/* Getting numbers from table */
values[4] = elements.get(4).text(); // NUMBER MAX VALUE
values[5] = elements.get(5).text(); // NUMBER MIDDLE VALUE
values[6] = elements.get(6).text(); // NUMBER MIN VALUE
return values;
}
#Override
public String[] doInBackground(Void... params) {
try {
URL url= new URL("http://www.mywebtoextractdata.com");
Document doc = Jsoup.connect(url.toString()).get();
getValuesGraph(doc);
getValuesFooter(doc);
/*
* Getting elements from the graphic in an array from 0-23. 0 it's 1:00am, 23 it's 00:00am
*/
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String[] values) {
/*tvactualval.setText();*/
tvmax.setText(values[4]);
tvmid.setText(values[5]);
tvmin.setText(values[6]);
/*System.out.println(val[4]);*/
super.onPostExecute(values);
}
}
}
Thank you in advance for your help and time.
In String[] doInBackground(Void... params) { you are supposed to return a String array. So create one
String arr [] = new String [2];
and then add the result of getValuesGraph() to it.
arr[0] = getValuesGraph(doc);
arr[1] = getValuesFooter(doc);
then return then arr

Passing data from one Java file to another in Android

I am a newbie to Android development. I have two Java files in my project. One file contains my main activity so I want to transfer the data from one Java file to another which contains the main activity.
cordovaExample.java:
package org.apache.cordova.example;
import android.content.Context;
import android.content.Intent;
import android.telephony.*;
import android.app.Activity;
import android.os.Bundle;
import android.widget.Toast;
import org.apache.cordova.*;
public class cordovaExample extends DroidGap
{
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
super.loadUrl("file:///android_asset/www/index.html");
Bundle extras = getIntent().getExtras();
String phno = extras.getString("novel.PhoneNumber");
Toast.makeText(getApplicationContext(),phno,Toast.LENGTH_LONG).show();
}
}
novel.java
package org.apache.cordova.example;
import android.content.Context;
import android.content.Intent;
import android.telephony.*;
import android.app.Activity;
import android.os.Bundle;
import android.widget.Toast;
public class novel extends Activity
{
public String PhoneNumber;
Context mcontext;
public String getNumber()
{
TelephonyManager tMgr=(TelephonyManager)mcontext.getSystemService(Context.TELEPHONY_SERVICE);
Intent intent = new Intent(this, cordovaExample.class);
intent.putExtra("novel.PhoneNumber", PhoneNumber);
startActivity(intent);
return PhoneNumber = tMgr.getLine1Number();
}
}
So i want to transfer the "PhoneNumber" from novel.java to cordovaExample.java but in novel.java, After running the application i am getting "unfortunately app has stopped" in emulator.
this is the logcat
08-12 15:49:37.657: E/AndroidRuntime(779): FATAL EXCEPTION: main
08-12 15:49:37.657: E/AndroidRuntime(779): java.lang.RuntimeException: Unable to start activity ComponentInfo{org.apache.cordova.example/org.apache.cordova.example.cordovaExample}: java.lang.NullPointerException
08-12 15:49:37.657: E/AndroidRuntime(779): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1956)
08-12 15:49:37.657: E/AndroidRuntime(779): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
08-12 15:49:37.657: E/AndroidRuntime(779): at android.app.ActivityThread.access$600(ActivityThread.java:123)
08-12 15:49:37.657: E/AndroidRuntime(779): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
08-12 15:49:37.657: E/AndroidRuntime(779): at android.os.Handler.dispatchMessage(Handler.java:99)
08-12 15:49:37.657: E/AndroidRuntime(779): at android.os.Looper.loop(Looper.java:137)
08-12 15:49:37.657: E/AndroidRuntime(779): at android.app.ActivityThread.main(ActivityThread.java:4424)
08-12 15:49:37.657: E/AndroidRuntime(779): at java.lang.reflect.Method.invokeNative(Native Method)
08-12 15:49:37.657: E/AndroidRuntime(779): at java.lang.reflect.Method.invoke(Method.java:511)
08-12 15:49:37.657: E/AndroidRuntime(779): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
08-12 15:49:37.657: E/AndroidRuntime(779): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
08-12 15:49:37.657: E/AndroidRuntime(779): at dalvik.system.NativeStart.main(Native Method)
08-12 15:49:37.657: E/AndroidRuntime(779): Caused by: java.lang.NullPointerException
08-12 15:49:37.657: E/AndroidRuntime(779): at org.apache.cordova.example.cordovaExample.onCreate(cordovaExample.java:20)
08-12 15:49:37.657: E/AndroidRuntime(779): at android.app.Activity.performCreate(Activity.java:4465)
08-12 15:49:37.657: E/AndroidRuntime(779): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
08-12 15:49:37.657: E/AndroidRuntime(779): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
08-12 15:49:37.657: E/AndroidRuntime(779): ... 11 more
Also, if I try the simple program I get the same result:
cordovaExample.java
package org.apache.cordova.example;
import android.content.Context;
import android.content.Intent;
import android.telephony.*;
import android.app.Activity;
import android.os.Bundle;
import android.widget.Toast;
import org.apache.cordova.*;
public class cordovaExample extends DroidGap
{
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
super.loadUrl("file:///android_asset/www/index.html");
novel c=new novel()
int a=c.getNumber();
Toast.makeText(getApplicationContext(),a,Toast.LENGTH_LONG).show();
}
}
novel.java
package org.apache.cordova.example;
import android.content.Context;
import android.content.Intent;
import android.telephony.*;
import android.app.Activity;
import android.os.Bundle;
import android.widget.Toast;
public class novel extends Activity
{
public int a=0;
public int getNumber()
{
a=5;
return a;
}
}
How can I resolve this?
you are using intent statement after return block
return PhoneNumber = tMgr.getLine1Number();
Intent myIntent = new Intent(novel.this, cordovaExample.class);
After return block any code show unreachable error .
After passing intent parameter then you can call return.
TelephonyManager tMgr=(TelephonyManager)mcontext.getSystemService(Context.TELEPHONY_SERVICE);
Intent intent = new Intent(this, cordovaExample.class);
intent.putExtra("novel.PhoneNumber", PhoneNumber);
startActivity(intent);
return PhoneNumber = tMgr.getLine1Number();
Android API guide contains a definitive FAQ item about how to pass data between between Activities/Services within a single application.
try this,
do like this in novel to set the phone number
Intent myIntent = new Intent(novel.this, cordovaExample.class);
myIntent.putExtra("phone", 989898989);
startActivity(myIntent);
in cordovaExample file do following to get the phoneNumber
Bundle b = this.getIntent().getExtras();
String i = b.getString("phone");
if you are not able to pass the data then alternative way is to declare public method and pass them, see following example,
novel.java
private static String phoneNumber = "";
public void onCreate()
{
...
phoneNumber = "9898989898";
...
}
public static String getPhoneNumber()
{
return phoneNumber;
}
cordovaExample.java
private static String phoneNumber = "";
phoneNumber = novel.getPhoneNumber();
Change your code to this : You got NPE in cordovaExample.java becaus in novel you put null PhoneNumber in Extra.
TelephonyManager tMgr=(TelephonyManager)mcontext.getSystemService(Context.TELEPHONY_SERVICE);
Intent intent = new Intent(this, cordovaExample.class);
PhoneNumber = tMgr.getLine1Number(); // Check PhoneNumber not null here before send to cordovaExample
if (PhoneNumber !=null ){
intent.putExtra("novel.PhoneNumber", PhoneNumber);
startActivity(intent);}
}

SAX parser raise some error

I got some issue with parsing, when I PHP based web service. I got stuck still from 2 day. I can't get any output in Activity. When I print it in Handler I got successfully print variable.
here are some logcate:
02-08 00:51:04.889: WARN/System.err(606): org.apache.harmony.xml.ExpatParser$ParseException: At line 1, column 805: not well-formed (invalid token)
02-08 00:51:04.893: WARN/System.err(606): at org.apache.harmony.xml.ExpatParser.parseFragment(ExpatParser.java:523)
02-08 00:51:04.893: WARN/System.err(606): at org.apache.harmony.xml.ExpatParser.parseDocument(ExpatParser.java:482)
02-08 00:51:04.893: WARN/System.err(606): at org.apache.harmony.xml.ExpatReader.parse(ExpatReader.java:320)
02-08 00:51:04.893: WARN/System.err(606): at org.apache.harmony.xml.ExpatReader.parse(ExpatReader.java:277)
02-08 00:51:04.893: WARN/System.err(606): at com.ESM.viewAllpartActivity.onCreate(viewAllpartActivity.java:69)
02-08 00:51:04.893: WARN/System.err(606): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
02-08 00:51:04.904: WARN/System.err(606): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
02-08 00:51:04.904: WARN/System.err(606): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
02-08 00:51:04.904: WARN/System.err(606): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
02-08 00:51:04.904: WARN/System.err(606): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
02-08 00:51:04.904: WARN/System.err(606): at android.os.Handler.dispatchMessage(Handler.java:99)
02-08 00:51:04.914: WARN/System.err(606): at android.os.Looper.loop(Looper.java:123)
02-08 00:51:04.914: WARN/System.err(606): at android.app.ActivityThread.main(ActivityThread.java:4627)
02-08 00:51:04.914: WARN/System.err(606): at java.lang.reflect.Method.invokeNative(Native Method)
02-08 00:51:04.914: WARN/System.err(606): at java.lang.reflect.Method.invoke(Method.java:521)
02-08 00:51:04.914: WARN/System.err(606): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
02-08 00:51:04.914: WARN/System.err(606): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
02-08 00:51:04.914: WARN/System.err(606): at dalvik.system.NativeStart.main(Native Method)
when I have call xml parsing.
here I have Past Code::-
package com.awe;
import java.net.URL;
import java.util.ArrayList;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
public class viewAllpartActivity extends Activity implements
OnItemClickListener {
/** Called when the activity is first created. */
/* declare widgets */
String nickname;
String type;
boolean flag = true;
ListView lview3;
blog_list_adapter adapter;
String[] str_blogImage;
String[] str_blogtitle;
String[] str_morelink;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view_allparty);
Button home_logout;
final Intent homeintent;
homeintent = new Intent(viewAllpartActivity.this, MainActivity.class);
home_logout = (Button) findViewById(R.id.vap_logout);
home_logout.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
startActivity(homeintent);
finish();
}
});
try {
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
/** Send URL to parse XML Tags */
URL sourceUrl = new URL(
"URL?api=ViewBooking_Admin");
/** Create handler to handle XML Tags ( extends DefaultHandler ) */
viewAllPartyHandler myXMLHandler = new viewAllPartyHandler();
xr.setContentHandler(myXMLHandler);
xr.parse(new InputSource(sourceUrl.openStream()));
viewAllPartydataset parsedLoginDataSet = myXMLHandler
.getParsedRegistrationData();
ArrayList<String> Bookingid = myXMLHandler.getbooking_id();
ArrayList<String> partyname = myXMLHandler.br3;
System.out.println("partyname :::: : "+partyname);
new xyz().execute();
} catch (Exception e) {
e.printStackTrace();
}
}
private class xyz extends AsyncTask<Void, Void, Void> {
private final ProgressDialog dialog = new ProgressDialog(
viewAllpartActivity.this);
#Override
protected void onPreExecute() {
this.dialog.setMessage("Please Wait...");
this.dialog.show();
this.dialog.setIndeterminate(true);
// put your code which preload with processDialog
}
#Override
protected Void doInBackground(Void... arg0) {
// put your code here
try {
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
/** Send URL to parse XML Tags */
URL sourceUrl = new URL(
"url?api=ViewBooking_Admin");
/** Create handler to handle XML Tags ( extends DefaultHandler ) */
viewAllPartyHandler myXMLHandler = new viewAllPartyHandler();
xr.setContentHandler(myXMLHandler);
xr.parse(new InputSource(sourceUrl.openStream()));
viewAllPartydataset parsedLoginDataSet = myXMLHandler
.getParsedRegistrationData();
ArrayList<String> Bookingid = myXMLHandler.getbooking_id();
ArrayList<String> partyname = myXMLHandler.br3;
System.out.println("partyname :::: : "+partyname);
/*str_blogImage = Bookingid.toArray(new String[Bookingid.size()]);
str_morelink = partyname.toArray(new String[partyname.size()]);*/
System.out.println("partyname :::: : "+partyname);
} catch (Exception e) {
// TODO: handle exception
}
return null;
}
#Override
protected void onPostExecute(final Void unused) {
lview3 = (ListView) findViewById(R.id.vap_listview);
/*lview3.setAdapter(new
ArrayAdapter<String>(viewAllpartActivity.this,android.R.layout.simple_list_item_1 ,
str_morelink));*/
lview3.setOnItemClickListener(viewAllpartActivity.this);
if (this.dialog.isShowing()) {
this.dialog.dismiss();
}
}
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
System.out.println("str_morelink ::: " + arg2);
Bundle b = new Bundle();
b.putString("url", str_morelink[arg2]);
Intent i1 = new Intent(getBaseContext(), blogwebview.class);
i1.putExtras(b);
startActivity(i1);
// finish();
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
Intent homeback;
homeback = new Intent(viewAllpartActivity.this, home.class);
startActivity(homeback);
return true;
}
return super.onKeyDown(keyCode, event);
}
}
There is problem with your xml and specially wiht '&' chararcters so you could define a CDTA section to hold the value...
Looking at your example here, it's not well formed. It contains not encoded '&' chararcters.
The right solution is to change the XML generating process in order to get well-formed XML files.
But you can try a workaround by replacing all "&" with "&", in your whole file, before you parse it.

Having trouble connecting to webservice through android

I am currently having trouble connecting to my webservice on android. I am using a Jetty web service and building it using ANT. On my laptop it works perfectly and displays items from my database. However it won't seem to connect on my Android application. Attached is the code and LOGCAT report.
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.Activity;
import android.os.Bundle;
import android.widget.EditText;
import android.widget.TextView;
public class Android2Servlet extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dbtest);
TextView txtresp = (TextView)findViewById(R.id.servlet_response);
String url = "http://(MY LAPTOPS IP):8085/DB";
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(url);
try{
System.out.println("About to execute");
HttpResponse response = client.execute(request);
String helpedResp=HttpUnpack.request(response);
System.out.println(helpedResp);
txtresp.setText(helpedResp);
System.out.println(response);
}catch(Exception ex){
txtresp.setText("Failed!");
ex.printStackTrace();
}
} }
The HTTP Unpack File
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpResponse;
public class HttpUnpack {
public static String request(HttpResponse response){
String result = "";
try{ InputStream in = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder str = new StringBuilder();
String line = null;
while((line = reader.readLine()) != null){
str.append(line + "\n");
}
in.close();
result = str.toString();
}catch(Exception ex){
result = "Error retrieving response";
}
return result;
}
}
The HTTP Unpack and the Android2Servlet do not cause any errors, however the text box only returns "Failed!".
LOGCAT file
W/System.err(1282): android.os.NetworkOnMainThreadException
W/System.err(1282): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1099)
W/System.err(1282): at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84)
W/System.err(1282): at libcore.io.IoBridge.connectErrno(IoBridge.java:127)
W/System.err(1282): at libcore.io.IoBridge.connect(IoBridge.java:112)
W/System.err(1282): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
W/System.err(1282): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459)
W/System.err(1282): at java.net.Socket.connect(Socket.java:842)
W/System.err(1282): at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:119)
W/System.err(1282): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:144)
W/System.err(1282): at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
W/System.err(1282): at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
W/System.err(1282): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
W/System.err(1282): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
W/System.err(1282): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
W/System.err(1282): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
W/System.err(1282): at myFood.myFood.Android2Servlet.onCreate(Android2Servlet.java:24)
W/System.err(1282): at android.app.Activity.performCreate(Activity.java:4465)
W/System.err(1282): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
W/System.err(1282): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
W/System.err(1282): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
W/System.err(1282): at android.app.ActivityThread.access$600(ActivityThread.java:123)
W/System.err(1282): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
W/System.err(1282): at android.os.Handler.dispatchMessage(Handler.java:99)
W/System.err(1282): at android.os.Looper.loop(Looper.java:137)
W/System.err(1282): at android.app.ActivityThread.main(ActivityThread.java:4424)
W/System.err(1282): at java.lang.reflect.Method.invokeNative(Native Method)
W/System.err(1282): at java.lang.reflect.Method.invoke(Method.java:511)
W/System.err(1282): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
W/System.err(1282): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
W/System.err(1282): at dalvik.system.NativeStart.main(Native Method)
Any response would be greatly helpful.
Regards.
EDIT:
I have now removed the network access and put it in another Java class. And called it form another class. And it is still returning the same errors. Any other advice?
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
public class androidconnectors {
public static final String main(String args[]) throws Exception {
String txtresp = "";
try{
String url = "http://(LAPTOPS IP):8085/Hello";
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(url);
System.out.println("About to execute");
HttpResponse response = client.execute(request);
String helpedResp=HttpUnpack.request(response); // Http Unpack is not part of
System.out.println(helpedResp); // of HttpClient library
txtresp =(helpedResp);
System.out.println(response);
}catch(Exception ex){
ex.printStackTrace();
}
return txtresp;
}
}
And the android class.
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class Settings extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dbtest);
Button mybutton = (Button) findViewById(R.id.buttonpress);
mybutton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
TextView txtresp = (TextView)findViewById(R.id.servlet_response);
String[] args = null;
try {
String x = androidconnectors.main(args);
txtresp.setText(x);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
txtresp.setText("Failed");
}
}
});
}
}
It would seem, based on a quick google search, that since Honeycomb you are not supposed to execute network access on your app's main thread (to improve responsiveness).
Create another thread for network access as suggested here.
You can't do Network Operations on the UI Thread better use AsyncTask/Service/IntentService
NetworkOnMainThreadException
The exception that is thrown when an application attempts to perform a
networking operation on its main thread.(Since API 11)
To resovled StrictMode issue you need to use below code in your activity -
static{
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}

Categories