java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0 - java

I'm new to android - I'm trying to populate textviews using data from external database but I'm receiving this error (LogCat below) I have had a long hard gander on the net but cant seem to find much to help me out.
LogCat
04-11 23:10:56.084: E/AndroidRuntime(333): FATAL EXCEPTION: main
04-11 23:10:56.084: E/AndroidRuntime(333): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.thickcrustdesigns.ufood/com.thickcrustdesigns.ufood.recipePage}: java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
04-11 23:10:56.084: E/AndroidRuntime(333): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)
04-11 23:10:56.084: E/AndroidRuntime(333): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
04-11 23:10:56.084: E/AndroidRuntime(333): at android.app.ActivityThread.access$1500(ActivityThread.java:117)
04-11 23:10:56.084: E/AndroidRuntime(333): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
04-11 23:10:56.084: E/AndroidRuntime(333): at android.os.Handler.dispatchMessage(Handler.java:99)
04-11 23:10:56.084: E/AndroidRuntime(333): at android.os.Looper.loop(Looper.java:123)
04-11 23:10:56.084: E/AndroidRuntime(333): at android.app.ActivityThread.main(ActivityThread.java:3683)
04-11 23:10:56.084: E/AndroidRuntime(333): at java.lang.reflect.Method.invokeNative(Native Method)
04-11 23:10:56.084: E/AndroidRuntime(333): at java.lang.reflect.Method.invoke(Method.java:507)
04-11 23:10:56.084: E/AndroidRuntime(333): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
04-11 23:10:56.084: E/AndroidRuntime(333): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
04-11 23:10:56.084: E/AndroidRuntime(333): at dalvik.system.NativeStart.main(Native Method)
04-11 23:10:56.084: E/AndroidRuntime(333): Caused by: java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
04-11 23:10:56.084: E/AndroidRuntime(333): at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:257)
04-11 23:10:56.084: E/AndroidRuntime(333): at java.util.ArrayList.get(ArrayList.java:311)
04-11 23:10:56.084: E/AndroidRuntime(333): at com.thickcrustdesigns.ufood.recipePage.onCreate(recipePage.java:44)
04-11 23:10:56.084: E/AndroidRuntime(333): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
04-11 23:10:56.084: E/AndroidRuntime(333): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
04-11 23:10:56.084: E/AndroidRuntime(333): ... 11 more
recipePage
package com.thickcrustdesigns.ufood;
import java.util.ArrayList;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.os.Bundle;
import android.content.Intent;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class recipePage extends Activity {
TextView txt_Recipe;
TextView txt_Ingredients;
TextView txt_Method;
Button btn_bk;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.recipepage);
Bundle data = getIntent().getExtras();
String recipe = data.getString("recipie");
ArrayList<NameValuePair> nvp = new ArrayList<NameValuePair>();
nvp.add(new BasicNameValuePair("request", "recipe"));
nvp.add(new BasicNameValuePair("recipe", recipe));
ArrayList<NameValuePair> nvp2 = new ArrayList<NameValuePair>();
nvp2.add(new BasicNameValuePair("request", "ingredients"));
nvp2.add(new BasicNameValuePair("recipe", recipe));
ArrayList<JSONObject> jsondefs = Request.fetchData(this, nvp);
String title = null;
try {
title = jsondefs.get(0).getString("Name");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String method = null;
try {
method = jsondefs.get(0).getString("Method");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ArrayList<JSONObject> jsonIngredients = Request.fetchData(this, nvp2);
String ingredients = "";
for (int i = 0; i < jsonIngredients.size(); i++){
String ji = null;
try {
ji = jsonIngredients.get(i).getString("Name") + "\n";
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ingredients += ji;
}
txt_Recipe.setText(title);
txt_Method.setText(method);
txt_Ingredients.setText(ingredients);
// Listening to button event
btn_bk.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
Intent i = new Intent(getApplicationContext(),
UFoodAppActivity.class);
startActivity(i);
}
});
}
}
request.java
package com.thickcrustdesigns.ufood;
import java.util.ArrayList;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
//import android.widget.TextView;
public class CatogPage extends ListActivity {
ListView listView1;
Button btn_bk;
String[] defs;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.definition_main);
btn_bk = (Button) findViewById(R.id.btn_bk);
listView1 = (ListView) findViewById(android.R.id.list);
ArrayList<NameValuePair> nvp = new ArrayList<NameValuePair>();
nvp.add(new BasicNameValuePair("request", "categories"));
ArrayList<JSONObject> jsondefs = Request.fetchData(this, nvp);
defs = new String[jsondefs.size()];
for (int i = 0; i < jsondefs.size(); i++) {
try {
defs[i] = jsondefs.get(i).getString("Name");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
uFoodAdapter adapter = new uFoodAdapter(this, R.layout.definition_list,
defs);
listView1.setAdapter(adapter);
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String item = defs[position];
Intent i = new Intent(getApplicationContext(), Results.class);
i.putExtra("category", item);
startActivity(i);
}
});
btn_bk.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
Intent i = new Intent(getApplicationContext(), CatogPage.class);
startActivity(i);
}
});
}
}
Many Thanks

Start looking on line 44 of recipePage.java
com.thickcrustdesigns.ufood.recipePage.onCreate(recipePage.java:44)
04-11 23:10:56.084: E/AndroidRuntime(333): at
android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
04-11 23:10:56.084: E/AndroidRuntime(333): at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
MORE DETAILS:
Following line is not filling jsondefs
ArrayList<JSONObject> jsondefs = Request.fetchData(this, nvp);

Looks like this call is unsafe:
ArrayList<JSONObject> jsondefs = Request.fetchData(this, nvp);
String title = null;
try {
title = jsondefs.get(0).getString("Name"); //<--- Here jsondefs could be empty
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if jsondefs is empty, you could see the error you are mentionning.

Most likely thrown by one of the jsondefs.get(0)… You should add an if(!jsondefs.isEmpty()) and an else that prints something so that you know what the problem is.

Related

How to Fix Unable to start activity ComponentInfo?

My problem is when I run app and click on register button suddenly displays the popup: "Force close"
Here is my code:
Main.java
package com.example.server;
import java.util.Timer;
import java.util.TimerTask;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class Main extends Activity {
private Button login,register,exit;
private EditText usertext,passtext;
public static String res="";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
login=(Button) findViewById(R.id.login);
register=(Button) findViewById(R.id.register);
exit=(Button) findViewById(R.id.exit);
usertext=(EditText) findViewById(R.id.usertext);
passtext=(EditText) findViewById(R.id.passtext);
login.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
login(usertext.getText().toString(),passtext.getText().toString());
}
});
register.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
Intent re=new Intent(Main.this,register.class);
startActivity(re);
}
});
exit.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
finish();
}
});
}
public void login(String user,String pass) {
new loginserver("http://ujo.ir/login,php",user,pass).execute();
final ProgressDialog pd=new ProgressDialog(Main.this);
pd.setMessage("Loading...");
pd.show();
final Timer tm=new Timer();
tm.schedule(new TimerTask() {
public void run() {
runOnUiThread(new Runnable() {
public void run() {
if(!res.equals("")){
pd.cancel();
Toast.makeText(getApplicationContext(), res, Toast.LENGTH_LONG).show();
res="";
tm.cancel();
}
}
});
}
}, 1, 1000);
}
}
register.java
import java.io.ObjectOutputStream.PutField;
import java.util.Timer;
import java.util.TimerTask;
import com.example.server.R.layout;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class register extends Activity {
public static String res="";
private Button register,exit;
private EditText name,family,user,pass,email;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.register);
exit.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
finish();
}
});
register.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
register1(name.getText().toString(),family.getText().toString(),user.getText().toString(),pass.getText().toString(),email.getText().toString());
}
});
}
public void register1(String name,String family,String user,String pass,String email) {
new registerserver("http://ujo.ir/register.php", name, family, user, pass, email).execute();
final ProgressDialog pd=new ProgressDialog(this);
pd.setMessage("Loading...");
pd.show();
final Timer tm=new Timer();
tm.scheduleAtFixedRate(new TimerTask() {
public void run() {
runOnUiThread(new Runnable() {
public void run() {
if(!res.equals("")) {
pd.cancel();
Toast.makeText(getApplicationContext(), res, Toast.LENGTH_LONG).show();
res="";
tm.cancel();
}
}
});
}
}, 1, 1000);
}
}
registerserver.java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import android.os.AsyncTask;
public class registerserver extends AsyncTask {
private String Name="";
private String Family="";
private String Link="";
private String User="";
private String Pass="";
private String Email="";
public registerserver(String link,String name,String family,String user,String pass,String email) {
name=Name;
family=Family;
link=Link;
user=User;
pass=Pass;
email=Email;
}
#Override
protected String doInBackground(Object... arg0) {
try {
String data=URLEncoder.encode("name","UTF8")+"="+URLEncoder.encode(Name,"UTF8");
data+="&"+URLEncoder.encode("family","UTF8")+"="+URLEncoder.encode(Family,"UTF8");
data+="&"+URLEncoder.encode("username","UTF8")+"="+URLEncoder.encode(User,"UTF8");
data+="&"+URLEncoder.encode("password","UTF8")+"="+URLEncoder.encode(Pass,"UTF8");
data+="&"+URLEncoder.encode("email","UTF8")+"="+URLEncoder.encode(Email,"UTF8");
data+="&"+URLEncoder.encode("status","UTF8")+"="+URLEncoder.encode("a","UTF8");
URL mylink=new URL(Link);
URLConnection connect=mylink.openConnection();
connect.setDoOutput(true);
OutputStreamWriter wr=new OutputStreamWriter(connect.getOutputStream());
wr.write(data);
wr.flush();
BufferedReader reader=new BufferedReader(new InputStreamReader(connect.getInputStream()));
StringBuilder sb=new StringBuilder();
String line=null;
while((line=reader.readLine()) != null) {
sb.append(line);
}
register.res=sb.toString();
} catch (Exception e) {}
return "";
}
}
and lastly, LogCat
08-04 21:19:11.704: D/AndroidRuntime(2066): Shutting down VM
08-04 21:19:11.704: W/dalvikvm(2066): threadid=1: thread exiting with uncaught exception (group=0xa000f180)
08-04 21:19:11.704: E/AndroidRuntime(2066): FATAL EXCEPTION: main
08-04 21:19:11.704: E/AndroidRuntime(2066): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.server/com.example.server.register}: java.lang.NullPointerException
08-04 21:19:11.704: E/AndroidRuntime(2066): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1956)
08-04 21:19:11.704: E/AndroidRuntime(2066): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
08-04 21:19:11.704: E/AndroidRuntime(2066): at android.app.ActivityThread.access$600(ActivityThread.java:123)
08-04 21:19:11.704: E/AndroidRuntime(2066): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
08-04 21:19:11.704: E/AndroidRuntime(2066): at android.os.Handler.dispatchMessage(Handler.java:99)
08-04 21:19:11.704: E/AndroidRuntime(2066): at android.os.Looper.loop(Looper.java:137)
08-04 21:19:11.704: E/AndroidRuntime(2066): at android.app.ActivityThread.main(ActivityThread.java:4424)
08-04 21:19:11.704: E/AndroidRuntime(2066): at java.lang.reflect.Method.invokeNative(Native Method)
08-04 21:19:11.704: E/AndroidRuntime(2066): at java.lang.reflect.Method.invoke(Method.java:511)
08-04 21:19:11.704: E/AndroidRuntime(2066): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
08-04 21:19:11.704: E/AndroidRuntime(2066): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
08-04 21:19:11.704: E/AndroidRuntime(2066): at dalvik.system.NativeStart.main(Native Method)
08-04 21:19:11.704: E/AndroidRuntime(2066): Caused by: java.lang.NullPointerException
08-04 21:19:11.704: E/AndroidRuntime(2066): at com.example.server.register.onCreate(register.java:30)
08-04 21:19:11.704: E/AndroidRuntime(2066): at android.app.Activity.performCreate(Activity.java:4465)
08-04 21:19:11.704: E/AndroidRuntime(2066): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
08-04 21:19:11.704: E/AndroidRuntime(2066): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
08-04 21:19:11.704: E/AndroidRuntime(2066): ... 11 more
08-04 21:19:11.724: D/dalvikvm(2066): GC_CONCURRENT freed 147K, 3% free 6716K/6919K, paused 0ms+0ms
08-04 21:19:12.174: I/dalvikvm(2066): threadid=3: reacting to signal 3
08-04 21:19:12.174: I/dalvikvm(2066): Wrote stack traces to '/data/anr/traces.txt'
08-04 21:19:12.234: I/dalvikvm(2066): threadid=3: reacting to signal 3
08-04 21:19:12.234: I/dalvikvm(2066): Wrote stack traces to '/data/anr/traces.txt'
You forgot to instanciate the Buttons "exit" and "register" in your register class activity. Thats why you get a nullpointer exception. By reading the Logs it is fairly simple to come to that conclusion ;)
And before you move on I would recommend to instanciate all the other elements btw!

mediaMetadataRetriever.setDataSource(getBaseContext(),uri) throws illegal argument exception

Hello developers I have a piece of that grabs the frames of a video...It seems it will work fine except a part of it where I am getting illegal argument exception...As I set the path of the video it crashes..Here is my code it crashes at the line
mediaMetadataRetriever.setDataSource(getBaseContext(),uri)
Here is the full code:
import java.io.IOException;
import android.graphics.Bitmap;
import android.media.MediaMetadataRetriever;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.res.AssetFileDescriptor;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.MediaController;
import android.widget.Toast;
import android.widget.VideoView;
public class MainActivity extends Activity {
MediaMetadataRetriever mediaMetadataRetriever;
MediaController myMediaController;
VideoView myVideoView;
String viewSource = "/storage/test.mp4";
// String viewSource = "/storage/test.mp4";
Uri uri = null;
#TargetApi(Build.VERSION_CODES.GINGERBREAD_MR1)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
AssetFileDescriptor afd = getAssets().openFd("test.mp4");
Log.v("MA", "Before setdatasource");
uri = Uri.parse("E:/test.mp4");
mediaMetadataRetriever = new MediaMetadataRetriever();
**mediaMetadataRetriever.setDataSource(getBaseContext(),uri);**
// mediaMetadataRetriever.setDataSource(afd.getFileDescriptor(),
// afd.getStartOffset(), afd.getLength());
Log.v("MA", "After setdatasource" + afd.getStartOffset());
myVideoView = (VideoView) findViewById(R.id.videoview);
Log.v("MA", "VIdeoview found");
myVideoView.setVideoURI(Uri.parse(viewSource));
Log.v("MA", "After setdatasource");
myMediaController = new MediaController(this);
Log.v("MA", "After setdatasource");
myVideoView.setMediaController(myMediaController);
Log.v("MA", "myMediaController initialised");
myVideoView.setOnCompletionListener(myVideoViewCompletionListener);
Log.v("MA", "setOnCompletionListener");
myVideoView.setOnPreparedListener(MyVideoViewPreparedListener);
Log.v("MA", "setOnPreparedListener");
myVideoView.setOnErrorListener(myVideoViewErrorListener);
Log.v("MA", "setOnErrorListener");
myVideoView.requestFocus();
Log.v("MA", "focus set");
myVideoView.start();
Log.v("MA", "video started");
Button buttonCapture = (Button) findViewById(R.id.capture);
buttonCapture.setOnClickListener(new OnClickListener() {
#TargetApi(Build.VERSION_CODES.GINGERBREAD_MR1)
#Override
public void onClick(View arg0) {
int currentPosition = myVideoView.getCurrentPosition(); // in
// millisecond
Toast.makeText(MainActivity.this,
"Current Position: " + currentPosition + " (ms)",
Toast.LENGTH_LONG).show();
Bitmap bmFrame = mediaMetadataRetriever
.getFrameAtTime(currentPosition * 1000); // unit in
// microsecond
if (bmFrame == null) {
Toast.makeText(MainActivity.this, "bmFrame == null!",
Toast.LENGTH_LONG).show();
} else {
AlertDialog.Builder myCaptureDialog = new AlertDialog.Builder(
MainActivity.this);
ImageView capturedImageView = new ImageView(
MainActivity.this);
capturedImageView.setImageBitmap(bmFrame);
LayoutParams capturedImageViewLayoutParams = new LayoutParams(
LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
capturedImageView
.setLayoutParams(capturedImageViewLayoutParams);
myCaptureDialog.setView(capturedImageView);
myCaptureDialog.show();
}
}
});
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
MediaPlayer.OnCompletionListener myVideoViewCompletionListener = new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer arg0) {
Toast.makeText(MainActivity.this, "End of Video", Toast.LENGTH_LONG)
.show();
}
};
MediaPlayer.OnPreparedListener MyVideoViewPreparedListener = new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
long duration = myVideoView.getDuration(); // in millisecond
Toast.makeText(MainActivity.this,
"Duration: " + duration + " (ms)", Toast.LENGTH_LONG)
.show();
}
};
MediaPlayer.OnErrorListener myVideoViewErrorListener = new MediaPlayer.OnErrorListener() {
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
Toast.makeText(MainActivity.this, "Error!!!", Toast.LENGTH_LONG)
.show();
return true;
}
};
}
Trace:
E/AndroidRuntime( 4317): FATAL EXCEPTION: main
E/AndroidRuntime( 4317): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.captureframe/com.example.captureframe.MainActivity}: java.lang.IllegalArgumentException
E/AndroidRuntime( 4317): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
E/AndroidRuntime( 4317): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
E/AndroidRuntime( 4317): at android.app.ActivityThread.access$600(ActivityThread.java:141)
E/AndroidRuntime( 4317): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
E/AndroidRuntime( 4317): at android.os.Handler.dispatchMessage(Handler.java:99)
E/AndroidRuntime( 4317): at android.os.Looper.loop(Looper.java:137)
E/AndroidRuntime( 4317): at android.app.ActivityThread.main(ActivityThread.java:5103)
E/AndroidRuntime( 4317): at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime( 4317): at java.lang.reflect.Method.invoke(Method.java:525)
E/AndroidRuntime( 4317): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
E/AndroidRuntime( 4317): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
E/AndroidRuntime( 4317): at dalvik.system.NativeStart.main(Native Method)
E/AndroidRuntime( 4317): Caused by: java.lang.IllegalArgumentException
E/AndroidRuntime( 4317): at android.media.MediaMetadataRetriever.setDataSource(MediaMetadataRetriever.java:165)
E/AndroidRuntime( 4317): at com.example.captureframe.MainActivity.onCreate(MainActivity.java:46)
E/AndroidRuntime( 4317): at android.app.Activity.performCreate(Activity.java:5133)
E/AndroidRuntime( 4317): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
E/AndroidRuntime( 4317): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
Any ideas will be really appreciated.
Use this method.
public static Bitmap retriveVideoFrameFromVideo(String videoPath)
throws Throwable
{
Bitmap bitmap = null;
MediaMetadataRetriever mediaMetadataRetriever = null;
try
{
mediaMetadataRetriever = new MediaMetadataRetriever();
if (Build.VERSION.SDK_INT >= 14)
mediaMetadataRetriever.setDataSource(videoPath, new HashMap<String, String>());
else
mediaMetadataRetriever.setDataSource(videoPath);
// mediaMetadataRetriever.setDataSource(videoPath);
bitmap = mediaMetadataRetriever.getFrameAtTime();
}
catch (Exception e)
{
e.printStackTrace();
throw new Throwable(
"Exception in retriveVideoFrameFromVideo(String videoPath)"
+ e.getMessage());
}
finally
{
if (mediaMetadataRetriever != null)
{
mediaMetadataRetriever.release();
}
}
return bitmap;
}

Runtime error with passing data between activities. Android

I really can't figure out what's the problem here, I did almost the same example i got from somewhere on net and it's working, but this one reports a runtime error when I click on the button to switch to secondActivity. But before I set up onActivityResult in first and sending result in second activity, it switched fine.
It's a little bit longer code, but it's nothing complicated. In first activity you click button to go to second activity, and there you pick two numbers, which are stored in object and sent by intent back to the first activity, and in first activity in textview you get the total of those numbers.
MainActivity
package com.example.parcelablevezba4;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
TextView tv1;
Button btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv1 = (TextView)findViewById(R.id.tv1);
btn = (Button)findViewById(R.id.btn);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Intent i = new Intent(MainActivity.this, SecondActivity.class);
startActivityForResult(i, 42);
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == 42){
if(resultCode == RESULT_OK){
Object obj2 = data.getParcelableExtra("obje");
int total = obj2.getFirstSummand() + obj2.getSecondSummand();
tv1.setText(obj2.getFirstSummand()+"+"+obj2.getSecondSummand()+"is "+total);
}else if(resultCode == RESULT_CANCELED){
Toast.makeText(getApplicationContext(), "CANCELED", Toast.LENGTH_SHORT).show();
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
SecondActivity
package com.example.parcelablevezba4;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.content.Intent;
public class SecondActivity extends Activity {
EditText et1;
EditText et2;
Button btnOk;
int firstSummand;
int secondSummand;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
et1 = (EditText)findViewById(R.id.etFirst);
et2 = (EditText)findViewById(R.id.etSecond);
btnOk = (Button)findViewById(R.id.btnOk);
firstSummand = Integer.parseInt(et1.getText().toString());
secondSummand = Integer.parseInt(et2.getText().toString());
btnOk.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent resultIntent = new Intent();
Object obj = new Object();
obj.setFirstSummand(firstSummand);
obj.setSecondSummand(secondSummand);
resultIntent.putExtra("obje", obj);
setResult(RESULT_OK,resultIntent);
finish();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.second, menu);
return true;
}
}
Object class
package com.example.parcelablevezba4;
import android.os.Parcel;
import android.os.Parcelable;
public class Object implements Parcelable {
private int firstSummand;
private int secondSummand;
public Object(){}
public Object(Parcel p){
this.firstSummand; = p.readInt();
this.secondSummand; = p.readInt();
}
public int getFirstSummand(){
return this.firstSummand;
}
public int getSecondSummand(){
return this.secondSummand;;
}
public void setFirstSummand(int f){
this.firstSummand = f;
}
public void setSecondSummand(int s){
this.secondSummand; = s;
}
#Override
public int describeContents() {
// TODO Auto-generated method stub
return 0;
}
#Override
public void writeToParcel(Parcel p, int flag) {
p.writeInt(firstSummand);
p.writeInt(secondSummand);
}
public static Parcelable.Creator<Object> CREATOR = new Parcelable.Creator<Object>() {
#Override
public Object createFromParcel(Parcel source) {
// TODO Auto-generated method stub
return new Object(source);
}
#Override
public Object[] newArray(int size) {
// TODO Auto-generated method stub
return new Object[size];
}
};
}
I translated this from my language, so if I mistyped somewhere sorry about that.
Error
08-17 13:20:22.933: E/AndroidRuntime(743): FATAL EXCEPTION: main
08-17 13:20:22.933: E/AndroidRuntime(743): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.parcelablevezba4/com.example.parcelablevezba4.SecondActivity}: java.lang.NumberFormatException: unable to parse '' as integer
08-17 13:20:22.933: E/AndroidRuntime(743): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)
08-17 13:20:22.933: E/AndroidRuntime(743): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
08-17 13:20:22.933: E/AndroidRuntime(743): at android.app.ActivityThread.access$1500(ActivityThread.java:117)
08-17 13:20:22.933: E/AndroidRuntime(743): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
08-17 13:20:22.933: E/AndroidRuntime(743): at android.os.Handler.dispatchMessage(Handler.java:99)
08-17 13:20:22.933: E/AndroidRuntime(743): at android.os.Looper.loop(Looper.java:123)
08-17 13:20:22.933: E/AndroidRuntime(743): at android.app.ActivityThread.main(ActivityThread.java:3683)
08-17 13:20:22.933: E/AndroidRuntime(743): at java.lang.reflect.Method.invokeNative(Native Method)
08-17 13:20:22.933: E/AndroidRuntime(743): at java.lang.reflect.Method.invoke(Method.java:507)
08-17 13:20:22.933: E/AndroidRuntime(743): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
08-17 13:20:22.933: E/AndroidRuntime(743): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
08-17 13:20:22.933: E/AndroidRuntime(743): at dalvik.system.NativeStart.main(Native Method)
08-17 13:20:22.933: E/AndroidRuntime(743): Caused by: java.lang.NumberFormatException: unable to parse '' as integer
08-17 13:20:22.933: E/AndroidRuntime(743): at java.lang.Integer.parseInt(Integer.java:362)
08-17 13:20:22.933: E/AndroidRuntime(743): at java.lang.Integer.parseInt(Integer.java:332)
08-17 13:20:22.933: E/AndroidRuntime(743): at com.example.parcelablevezba4.SecondActivity.onCreate(SecondActivity.java:30)
08-17 13:20:22.933: E/AndroidRuntime(743): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
08-17 13:20:22.933: E/AndroidRuntime(743): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
08-17 13:20:22.933: E/AndroidRuntime(743): ... 11 more
It looks like one of your EditTexts are returning an empty string:
firstSummand = Integer.parseInt(et1.getText().toString());
secondSummand = Integer.parseInt(et2.getText().toString());
And then you try to parse that empty string.
Add a log before or even better a check:
String edit1 = et1.getText().toString();
String edit2 = et2.getText().toString();
Log.e("TAG", "First: "+edit1+" Second: "+edit2);
firstSummand = (edit1.isEmpty()) ? 0 : Integer.parseInt(edit1);
secondSummand = (edit2.isEmpty()) ? 0 : Integer.parseInt(edit2);

android app crashes when killing one activity and start another one

There is one button I set in Scene2.java.I want to use the button to get in other activities Scene3.java,GameOver.java Everything worked fine until its about to open the new activity,every time the app crashed there. I want to know if there're any mistake I made in the connection,which I mean the newIntent and getIntent inScene2.java GameOver.javaand Scene3.java
Scene2.java
package com.group5.littlered;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class Scene2 extends Activity {
MediaPlayer bird;
MediaPlayer bgm;
int position = 0;
String[] conversation;
TextView frame;
ImageView conframe;
final String[] ListStr = { "Wake up and ask her", "Peek her secretly" };
int plot = 0;
#Override
public void onBackPressed() {
}
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
// Remove title bar
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
// Remove notification bar
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_scene2);
Intent intent1 = getIntent();
conversation = getResources().getStringArray(R.array.scene2);
frame = (TextView) findViewById(R.id.textView1);
Button next = (Button) findViewById(R.id.wtf);
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (position < 2) {
String sentence = conversation[position];
frame.setText(sentence + "");
position++;
} else {
if (plot < 1) {
AlertDialog choice = new AlertDialog.Builder(
Scene2.this).create();
choice.setTitle("Pick a choice");
choice.setMessage(" ");
choice.setButton("Get up and ask her what happened",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
plot = 1;
}
});
choice.setButton2("Peek her secretly",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
plot = 2;
position = 4;
}
});
choice.show();
} else {
if (plot < 2) {
if (position < 4) {
String sentence = conversation[position];
frame.setText(sentence + "");
position++;
} else {
Intent intent2 = new Intent(Scene2.this,
GameOver.class);
startActivity(intent2);
finish();
}
} else {
if (position < 6) {
String sentence = conversation[position];
frame.setText(sentence + "");
position++;
} else {
Intent intent3 = new Intent(Scene2.this,
Scene3.class);
startActivity(intent3);
finish();
}
}
}
}
}
});
// BGM
bgm = MediaPlayer.create(Scene2.this, R.raw.voyager);
bgm.setLooping(true);
bgm.start();
// bird
bird = MediaPlayer.create(Scene2.this, R.raw.bird);
bird.setLooping(false);
bird.start();
}
}
Scene3.java
package com.group5.littlered;
import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
public class Scene3 extends Activity {
int position = 0;
String[] conversation;
TextView frame;
ImageView conframe;
#Override
public void onBackPressed() {
}
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
// Remove title bar
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
// Remove notification bar
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_scene3);
Intent intent3 = getIntent();
conversation = getResources().getStringArray(R.array.scene1);
frame = (TextView) findViewById(R.id.textView1);
Button next = (Button) findViewById(R.id.wtf);
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (position < 6) {
String sentence = conversation[position];
frame.setText(sentence + "");
position++;
} else {
{
}
}
}
});
}
}
Again sorry for my poor ENGLISH, plz tell me what I need to post more to help you understand my problem.
my logcat
04-30 09:37:39.497: E/AndroidRuntime(4862): FATAL EXCEPTION: main
04-30 09:37:39.497: E/AndroidRuntime(4862): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.group5.littlered/com.group5.littlered.Scene3}: java.lang.NullPointerException
04-30 09:37:39.497: E/AndroidRuntime(4862): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
04-30 09:37:39.497: E/AndroidRuntime(4862): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
04-30 09:37:39.497: E/AndroidRuntime(4862): at android.app.ActivityThread.access$600(ActivityThread.java:141)
04-30 09:37:39.497: E/AndroidRuntime(4862): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
04-30 09:37:39.497: E/AndroidRuntime(4862): at android.os.Handler.dispatchMessage(Handler.java:99)
04-30 09:37:39.497: E/AndroidRuntime(4862): at android.os.Looper.loop(Looper.java:137)
04-30 09:37:39.497: E/AndroidRuntime(4862): at android.app.ActivityThread.main(ActivityThread.java:5103)
04-30 09:37:39.497: E/AndroidRuntime(4862): at java.lang.reflect.Method.invokeNative(Native Method)
04-30 09:37:39.497: E/AndroidRuntime(4862): at java.lang.reflect.Method.invoke(Method.java:525)
04-30 09:37:39.497: E/AndroidRuntime(4862): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
04-30 09:37:39.497: E/AndroidRuntime(4862): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
04-30 09:37:39.497: E/AndroidRuntime(4862): at dalvik.system.NativeStart.main(Native Method)
04-30 09:37:39.497: E/AndroidRuntime(4862): Caused by: java.lang.NullPointerException
04-30 09:37:39.497: E/AndroidRuntime(4862): at com.group5.littlered.Scene3.onCreate(Scene3.java:45)
04-30 09:37:39.497: E/AndroidRuntime(4862): at android.app.Activity.performCreate(Activity.java:5133)
04-30 09:37:39.497: E/AndroidRuntime(4862): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
04-30 09:37:39.497: E/AndroidRuntime(4862): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
04-30 09:37:39.497: E/AndroidRuntime(4862): ... 11 more
The line that is crashing is the line 45 of Scene3:
Button next = (Button) findViewById(R.id.wtf);
next.setOnClickListener(new View.OnClickListener() { // <-- THIS ONE
...
});
The cause is a NullPointerException. This means that the identifier "wtf" exists in R (this wouldn't compile otherwise) but is not found in the layer activity_scene3, as we wave the following statement line 38 of Scene3.onCreate():
setContentView(R.layout.activity_scene3); // and later on findViewById() returns `null`
You have to revisit this layout to ensure that the Button you are willing to access to actually exists, with the ID wtf.
Generally speaking, this is the danger in using a same ID in different layouts. This is prone to hide errors that would easily be found otherwise as this would just not compile.
Check your manifest file and add Scene3.java in it
<activity
android:name=".Scene3" >
</activity>
Always post question with exception, second this is may be you have not mention your other activity in manifest file like:
<activity
android:name=".Scene3">
</activity>
<activity
android:name=".GameOver">
</activity>

Unable to retrieve the value of textfield

i am the newbee in Android Development.
I had developed an app contains a login, the credentials must be passed in the text field and later it will call a webservice.
I am facing the issue as user and password is not getting copied at the required position.
Please help me out.
package com.authorwjf.http_get;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class Main extends Activity implements OnClickListener {
EditText txtUserName;
EditText txtPassword;
#Override
public void onCreate(Bundle savedInstanceState) {
txtUserName=(EditText)this.findViewById(R.id.editText1);
txtPassword=(EditText)this.findViewById(R.id.editText2);
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
findViewById(R.id.my_button).setOnClickListener(this);
}
#Override
public void onClick(View arg0) {
Button b = (Button)findViewById(R.id.my_button);
b.setClickable(false);
new LongRunningGetIO().execute();
}
private class LongRunningGetIO extends AsyncTask <Void, Void, String> {
protected String getASCIIContentFromEntity(HttpEntity entity) throws IllegalStateException, IOException {
InputStream in = entity.getContent();
StringBuffer out = new StringBuffer();
int n = 1;
while (n>0) {
byte[] b = new byte[4096];
n = in.read(b);
if (n>0) out.append(new String(b, 0, n));
}
return out.toString();
}
#Override
protected String doInBackground(Void... params) {
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
String user= txtUserName.getText().toString();
String pass= txtPassword.getText().toString();
System.out.println("USERRRR"+user);
System.out.println(pass);
//String user="at#ril.com";
//String pass= "123456";
String accessTokenQry = "{"+
"\"uid\":\""+user+"\","+
"\"password\":\""+pass+"\","+
"\"consumptionDeviceId\":\"fder-et3w-3adw2-2erf\","+
"\"consumptionDeviceName\":\"Samsung Tab\""+
"}";
HttpPost httpPost = new HttpPost("http://devssg01.ril.com:8080/v2/dip/auth/login");
httpPost.setHeader("Content-Type",
"application/json");
httpPost.setHeader("X-API-Key",
"l7xx7914b8704b2d4b029ab9c4b1b9c66dbf");
StringEntity input;
try {
input = new StringEntity(accessTokenQry);
httpPost.setEntity(input);
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String text = null;
try {
HttpResponse response = httpClient.execute(httpPost, localContext);
HttpEntity entity = response.getEntity();
text = getASCIIContentFromEntity(entity);
} catch (Exception e) {
return e.getLocalizedMessage();
}
return text;
}
protected void onPostExecute(String results) {
if (results!=null) {
EditText et = (EditText)findViewById(R.id.my_edit);
et.setText(results);
}
Button b = (Button)findViewById(R.id.my_button);
b.setClickable(true);
}
}
}
The LogCat Output is:
08-10 01:20:23.977: W/dalvikvm(760): threadid=14: thread exiting with uncaught exception (group=0x414c4700)
08-10 01:20:23.984: E/AndroidRuntime(760): FATAL EXCEPTION: AsyncTask #4
08-10 01:20:23.984: E/AndroidRuntime(760): java.lang.RuntimeException: An error occured while executing doInBackground()
08-10 01:20:23.984: E/AndroidRuntime(760): at android.os.AsyncTask$3.done(AsyncTask.java:299)
08-10 01:20:23.984: E/AndroidRuntime(760): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
08-10 01:20:23.984: E/AndroidRuntime(760): at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
08-10 01:20:23.984: E/AndroidRuntime(760): at java.util.concurrent.FutureTask.run(FutureTask.java:239)
08-10 01:20:23.984: E/AndroidRuntime(760): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
08-10 01:20:23.984: E/AndroidRuntime(760): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
08-10 01:20:23.984: E/AndroidRuntime(760): at java.lang.Thread.run(Thread.java:841)
08-10 01:20:23.984: E/AndroidRuntime(760): Caused by: java.lang.NullPointerException
08-10 01:20:23.984: E/AndroidRuntime(760): at com.authorwjf.http_get.Main$LongRunningGetIO.doInBackground(Main.java:66)
08-10 01:20:23.984: E/AndroidRuntime(760): at com.authorwjf.http_get.Main$LongRunningGetIO.doInBackground(Main.java:1)
08-10 01:20:23.984: E/AndroidRuntime(760): at android.os.AsyncTask$2.call(AsyncTask.java:287)
08-10 01:20:23.984: E/AndroidRuntime(760): at java.util.concurrent.FutureTask.run(FutureTask.java:234)
08-10 01:20:23.984: E/AndroidRuntime(760): ... 3 more
You are trying to initialize EditTexts before layout loaded.
If you want to get EditText on layout, you must initialize it after layout loaded.
Here is correct code:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
findViewById(R.id.my_button).setOnClickListener(this);
txtUserName=(EditText)this.findViewById(R.id.editText1);
txtPassword=(EditText)this.findViewById(R.id.editText2);
}
use this
EditText textw3d =(EditText) findViewById(R.id.editText3d);
final String strd3d = textw3d.getText().toString();
I suggest following change in your code.
Just write following lines
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
above
txtUserName=(EditText)this.findViewById(R.id.editText1);
txtPassword=(EditText)this.findViewById(R.id.editText2);
Move the lines where you get the reference to text views after the setContentView function call:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
findViewById(R.id.my_button).setOnClickListener(this);
txtUserName=(EditText)this.findViewById(R.id.editText1);
txtPassword=(EditText)this.findViewById(R.id.editText2);
}
The fact is you need to call setContentView before initializing any widget in your layout because this is the call that "loads" your layout defined in layout_main.xml file into your activity.
Thanks a lot Guyz,
The issue is resolved now.
Special appreciation to JustWork
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
findViewById(R.id.my_button).setOnClickListener(this);
txtUserName=(EditText)this.findViewById(R.id.editText1);
txtPassword=(EditText)this.findViewById(R.id.editText2);
}

Categories