When I copy past the working code from the fragment to the dialogfragment suddenly it doesn't work.
on regular fragment: save the bitmap on sd card.
on dialogfragment: doesn't save the bitmap on sd card.
dialog fragment:
package com.example.smite.floater;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Environment;
import android.text.Layout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
/**
* Created by smite on 09/08/2015.
*/
public class DialogEditText extends DialogFragment {
TextView textView;
ImageView img;
Bitmap bitmap;
BitmapDrawable drawable;
EditText editText;
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
builder.setView(inflater.inflate(R.layout.dialogedittext, null));
builder.setTitle("Pick a name");
View creatorLayout = inflater.inflate(R.layout.creator, null);
textView = (TextView)creatorLayout.findViewById(R.id.textView);
img = (ImageView)creatorLayout.findViewById(R.id.img);
editText =(EditText)getActivity().findViewById(R.id.edittext);
builder.setPositiveButton("save", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
textView.buildDrawingCache();
Log.d("d", "buildDrawingCache");
img.setImageBitmap(textView.getDrawingCache());
Log.d("d", "buildDrawingCache2");
drawable = (BitmapDrawable) img.getDrawable();
bitmap = drawable.getBitmap();
File sdCardDirectory = Environment.getExternalStorageDirectory();
File image = new File(sdCardDirectory, "edittext.png");
Log.d("d", "created image");
boolean success = false;
FileOutputStream outputStream;
try {
outputStream = new FileOutputStream(image);
Log.d("d", "created image");
//line : 79 bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream);
outputStream.flush();
outputStream.close();
}catch (FileNotFoundException ex1) {
ex1.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}
});
builder.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
DialogEditText.this.getDialog().cancel();
}
});
return builder.show();
}
}
logcat error:
08-10 04:06:56.566 16710-16710/com.example.smite.floater E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.smite.floater, PID: 16710
java.lang.NullPointerException
at com.example.smite.floater.DialogEditText$1.onClick(DialogEditText.java:79)
at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:166)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5001)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
craetor xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/siganture_creator"
android:hint="#string/signature..."
android:imeOptions="actionDone|flagNoExtractUi"
android:inputType="text"
android:layout_marginTop="30dp"
/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="200dp"
android:gravity="center"
android:layout_gravity="center">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/signature..."
android:id="#+id/textView"
android:textSize="50dp"
/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/img"
android:visibility="gone"
/>
</LinearLayout>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="save"
android:id="#+id/save"
android:layout_marginTop="10dp"
/>
</LinearLayout>
Thanks for helping guys (:
To get a bitmap from a view, view should be drawn. In your case you are inflating R.layout.creato layout, getting an instance of it and you have not used setView() or addView() method to draw that layout. In other word you have created just a different instance of creator layout and it is not displayed yet thats why bitmap is null.
Try using getActivity() method to get instead of creatorLayout variable. It should help you. it will find view in activity scope.
Have a look at following edited code:
Edited
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setView(inflater.inflate(R.layout.dialogedittext, null));
builder.setTitle("Pick a name");
textView = (TextView)getActivity().findViewById(R.id.textView);
img = (ImageView)getActivity().findViewById(R.id.img);
editText =(EditText)getActivity().findViewById(R.id.edittext);
builder.setPositiveButton("save", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
textView.buildDrawingCache();
Log.d("d", "buildDrawingCache");
img.setImageBitmap(textView.getDrawingCache());
Log.d("d", "buildDrawingCache2");
drawable = (BitmapDrawable) img.getDrawable();
bitmap = drawable.getBitmap();
File sdCardDirectory = Environment.getExternalStorageDirectory();
File image = new File(sdCardDirectory, "edittext.png");
Log.d("d", "created image");
boolean success = false;
FileOutputStream outputStream;
try {
outputStream = new FileOutputStream(image);
Log.d("d", "created image");
//line : 79 bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream);
outputStream.flush();
outputStream.close();
}catch (FileNotFoundException ex1) {
ex1.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}
});
builder.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
DialogEditText.this.getDialog().cancel();
}
});
return builder.show();
}
Related
EDIT
Got the error, it turns out it is an issue regarding the API version of the emulator. Works fine in higher API version
I am new to Android development and I am trying to build a simple to-do list where items will be added to ListView when a button is clicked. The problem is, the items are not shown in the listview, although they are added and deleted. Please help me identify what I am doing wrong.
Here is my activity_main.xml file
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.erfan.todolist.MainActivity">
<RelativeLayout
android:layout_width="368dp"
android:layout_height="495dp"
tools:layout_editor_absoluteX="8dp"
tools:layout_editor_absoluteY="8dp">
<EditText
android:id="#+id/editTextAddItem"
android:hint="Enter Item"
android:layout_width="250dp"
android:layout_height="50dp"
android:layout_weight="4"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true" />
<Button
android:id="#+id/buttonAddItem"
android:text="Add"
android:layout_width="100dp"
android:layout_height="50dp"
android:layout_alignParentTop="true"
android:layout_alignParentEnd="true" />
<ListView
android:id="#+id/listView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentStart="true"
android:layout_below="#+id/editTextAddItem"
android:layout_marginTop="23dp" />
</RelativeLayout>
</android.support.constraint.ConstraintLayout>
Here is my MainActivity.java file
package com.example.erfan.todolist;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
EditText vEditTextAddItem;
Button vButtonAddItem;
ListView vListViewItemList;
ArrayList<String> items;
ArrayAdapter<String> adapter;
public static final String FILENAME = "data.dat";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
vEditTextAddItem = (EditText) findViewById(R.id.editTextAddItem);
vButtonAddItem = (Button) findViewById(R.id.buttonAddItem);
vListViewItemList = (ListView) findViewById(R.id.listView);
items = readData(getApplicationContext());
adapter = new ArrayAdapter<String>(getApplicationContext(), R.layout.support_simple_spinner_dropdown_item, items);
vListViewItemList.setAdapter(adapter);
vButtonAddItem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.buttonAddItem:
String itemEntered = vEditTextAddItem.getText().toString();
adapter.add(itemEntered);
vEditTextAddItem.setText("");
writeData(items, getApplicationContext());
Toast.makeText(getApplicationContext(), "Item is added", Toast.LENGTH_SHORT).show();
break;
}
}
});
vListViewItemList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
items.remove(position);
adapter.notifyDataSetChanged();
Toast.makeText(getApplicationContext(), "Item Deleted", Toast.LENGTH_SHORT).show();
}
});
}
public static void writeData(ArrayList<String> items, Context context) {
try {
FileOutputStream fileOutputStraStream = context.openFileOutput(FILENAME, Context.MODE_PRIVATE);
ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStraStream);
objectOutputStream.writeObject(items);
objectOutputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static ArrayList<String> readData(Context context) {
ArrayList<String> itemList = null;
try {
FileInputStream fileInputStream = context.openFileInput(FILENAME);
ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
itemList = (ArrayList<String>) objectInputStream.readObject();
} catch (FileNotFoundException e) {
itemList = new ArrayList<>();
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
itemList = new ArrayList<>();
e.printStackTrace();
}
return itemList;
}
}
I am attaching the screenshot of the emulator as well
When the item is added, no item is showing in the ListView.
Got the error, it turns out it is an issue regarding the API version of the emulator. Works fine in higher API version
That is my code java
intent.putExtra(Intent.EXTRA_SUBJECT, "My App name and some text");
intent.putExtra(Intent.EXTRA_TEXT, "a link");
intent.putExtra(Intent.EXTRA_STREAM,getImageUri(context,mBitmap));
intent.setType("image/*,text/plain");
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
I want to share image and text. This code works on WhatsApp, Twitter, Gmail , etc .. but it does not work on Facebook
thank you in advance for your help
If you want to share the Image and text on Facebook without using Facebook SDK then you have to create the bitmap of your image plus text and then you can share that bitmap on facebook.
Download the source code from here (Share image and text on facebook using intent in android)
activity_main.xml
<RelativeLayout android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffffff"
xmlns:android="http://schemas.android.com/apk/res/android">
<EditText
android:id="#+id/et_text"
android:layout_width="match_parent"
android:textSize="15dp"
android:layout_height="45dp"
android:layout_marginTop="10dp"
android:background="#drawable/edittext_drawable"
android:hint="Enter your text"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:paddingRight="10dp"
android:inputType="text"
android:imeOptions="actionDone"
android:paddingLeft="10dp"
android:singleLine="true"
android:textColorHint="#979797" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/rl_main"
android:background="#ffffff"
android:layout_below="#+id/et_text"
android:layout_above="#+id/tv_share">
<ImageView
android:layout_width="match_parent"
android:layout_height="250dp"
android:src="#drawable/index"
android:scaleType="fitXY"
android:id="#+id/iv_image"
android:layout_marginTop="10dp"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="15dp"
android:id="#+id/tv_text"
android:layout_below="#+id/iv_image"
android:layout_margin="10dp"
android:textColor="#000000"
android:maxLines="5"
/>
</RelativeLayout>
<TextView
android:id="#+id/tv_share"
android:layout_width="match_parent"
android:layout_height="50dp"
android:background="#F38D0A"
android:gravity="center"
android:padding="10dp"
android:layout_margin="10dp"
android:text="Share"
android:textColor="#ffffff"
android:textSize="15dp"
android:layout_alignParentBottom="true"/>
</RelativeLayout>
MainActivity.java
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
EditText et_text;
ImageView iv_image;
TextView tv_share,tv_text;
RelativeLayout rl_main;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
}
private void init(){
et_text = (EditText)findViewById(R.id.et_text);
iv_image = (ImageView)findViewById(R.id.iv_image);
tv_share = (TextView)findViewById(R.id.tv_share);
rl_main = (RelativeLayout)findViewById(R.id.rl_main);
tv_text= (TextView) findViewById(R.id.tv_text);
File dir = new File("/sdcard/Testing/");
try {
if (dir.mkdir()) {
System.out.println("Directory created");
} else {
System.out.println("Directory is not created");
}
} catch (Exception e) {
e.printStackTrace();
}
tv_share.setOnClickListener(this);
et_text.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
tv_text.setText(et_text.getText().toString());
}
});
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.tv_share:
Bitmap bitmap1 = loadBitmapFromView(rl_main, rl_main.getWidth(), rl_main.getHeight());
saveBitmap(bitmap1);
String str_screenshot = "/sdcard/Testing/"+"testing" + ".jpg";
fn_share(str_screenshot);
break;
}
}
public void saveBitmap(Bitmap bitmap) {
File imagePath = new File("/sdcard/Testing/"+"testing" + ".jpg");
FileOutputStream fos;
try {
fos = new FileOutputStream(imagePath);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.flush();
fos.close();
Log.e("ImageSave", "Saveimage");
} catch (FileNotFoundException e) {
Log.e("GREC", e.getMessage(), e);
} catch (IOException e) {
Log.e("GREC", e.getMessage(), e);
}
}
public static Bitmap loadBitmapFromView(View v, int width, int height) {
Bitmap b = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(b);
v.draw(c);
return b;
}
public void fn_share(String path) {
File file = new File("/mnt/" + path);
Bitmap bmp = BitmapFactory.decodeFile(file.getAbsolutePath());
Uri uri = Uri.fromFile(file);
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("image/*");
intent.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(Intent.createChooser(intent, "Share Image"));
}
}
Thanks!
You can share int value of an image as R.drawable.image and get it with getResources.getDrawable(int)
I wanted to make my app be able to take proper screenshots like my own device does on touch of a button but it appears that it just takes screenshot of the view. What I want is to be able to take full screenshots with whatever it is on the screen like my device does.
Here's my java code:
package com.arvisapps.lazyscreenshot;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
public class MainActivity extends Activity {
RelativeLayout R1;
ImageView img;
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
private void showNotification() {
builder.setAutoCancel(false);
builder.setContentTitle("Take Screenshot");
builder.setContentText("");
builder.setSmallIcon(R.drawable.ic_notification);
builder.setOngoing(true);
Notification notification = builder.build();
NotificationManager manager = (NotificationManager) this.getSystemService(NOTIFICATION_SERVICE);
manager.notify(1, notification);
}
private void dontShowNotification(){
NotificationManager nMgr = (NotificationManager) this.getSystemService(NOTIFICATION_SERVICE);
nMgr.cancel(1);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
R1 = (RelativeLayout) findViewById(R.id.relatv);
CheckBox cb1 = (CheckBox) findViewById(R.id.cb_1);
cb1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked == true) {
showNotification();
} else if (isChecked == false) {
dontShowNotification();
}
}
});
}
public void takeScreenshot(View v)
{
View v1 = R1.getRootView();
v1.setDrawingCacheEnabled(true);
Bitmap bm = v1.getDrawingCache();
BitmapDrawable bmDrawable = new BitmapDrawable(bm);
img = (ImageView) findViewById(R.id.screenshots);
img.setBackgroundDrawable(bmDrawable);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, 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);
}
}
Here's my XML:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/relatv"
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=".MainActivity">
<RelativeLayout
android:id="#+id/cb1_grp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true">
<TextView
android:id="#+id/cb1_txtvw"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="15dp"
android:text="#string/cb1_txt" />
<CheckBox
android:id="#+id/cb_1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#id/cb1_txtvw"
android:layout_marginLeft="107dp"
android:layout_marginStart="107dp"/>
</RelativeLayout>
<LinearLayout
android:id="#+id/edittxt_grp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/cb1_grp"
android:layout_centerHorizontal="true">
<TextView
android:id="#+id/edittxt_txtvw"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/delaytime" />
<EditText
android:id="#+id/edittxt_delay"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="number"/>
</LinearLayout>
<Button
android:id="#+id/btn1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/edittxt_grp"
android:layout_centerHorizontal="true"
android:text="#string/btn1_txt"
android:onClick="takeScreenshot"/>
<ImageView
android:layout_below="#id/btn1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/screenshots"
android:contentDescription="#string/app_name"
/>
If your phone is rooted try.
Process sh = Runtime.getRuntime().exec("su", null,null);
OutputStream os = sh.getOutputStream();
os.write(("/system/bin/screencap -p " + "/sdcard/img.png").getBytes("ASCII"));
os.flush();
os.close();
sh.waitFor();
then read img.png as bitmap and convert it jpg as follows
Bitmap screen = BitmapFactory.decodeFile(Environment.getExternalStorageDirectory()+
File.separator +"img.png");
//my code for saving
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
screen.compress(Bitmap.CompressFormat.JPEG, 15, bytes);
//you can create a new file name "test.jpg" in sdcard folder.
File f = new File(Environment.getExternalStorageDirectory()+ File.separator + "test.jpg");
f.createNewFile();
//write the bytes in file
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
// remember close de FileOutput
fo.close();
The method you're using, getDrawingCache() will only get that view's drawing cache. Unfortunately, an application cannot directly access the framebuffer (and thus the raw pixels) unless your device is rooted so you won't be able to take a full screenshot from your app.
I am new to programming and started with android development out of passion and this is my second application.
I looked into android tutorials online and was trying to do this:
1. Record button in mainaactivity
2. On-click opens up a dialog box which gives options to record.
3. Dialog box has four buttons (Start, Stop, Playback, Stop Playback).
What is working:
1. On click shows a dialog box, but no options in it.
2. Record works, when played as a different activity.
I believe I have missed something, can someone help?
//MainActivity.java
import android.app.AlertDialog;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.support.v4.app.DialogFragment;
import android.view.View;
public class MainActivity extends FragmentActivity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void RecordClick(View v){
RecordDialog dialog = new RecordDialog();
dialog.show(getFragmentManager(),"Record_Dialog");
}
}
//Dialog.java
package com.example.record;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.View;
import java.io.File;
import java.io.IOException;
public class RecordDialog extends DialogFragment{
View v;
private MediaPlayer mediaPlayer;
private MediaRecorder mediaRecorder;
private String store_file;
/* #Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
LayoutInflater inflator = getActivity().getLayoutInflater();
v = inflator.inflate(R.layout.customdialog, null);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setView(v).setPositiveButton("DONE", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
}).setNegativeButton("CANCEL", new DialogInterface.OnClickListener(){
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
return builder.create();
}
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LayoutInflater inflator = getActivity().getLayoutInflater();
v = inflator.inflate(R.layout.customdialog, null);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
store_file= Environment.getExternalStorageDirectory()+"/audiorecorder.3gpp";
}
public void onButtonClick(View v){
switch (v.getId()){
case R.id.Startbtn:
try{
startRecording();
}
catch(Exception e){
e.printStackTrace();
}break;
case R.id.Stopbtn:
try{
stopRecording();
}
catch(Exception e){
e.printStackTrace();
}break;
case R.id.PlayBackbtn:
try{
startPlayBack();
}
catch(Exception e){
e.printStackTrace();
}break;
case R.id.StopPlayingbtn:
try{
stopPlayBack();
}
catch(Exception e){
e.printStackTrace();
}break;
}
}
private void startRecording() throws IOException {
discardMediaRecorder();
File storeFile= new File(store_file);
if(storeFile.exists())
storeFile.delete();
mediaRecorder = new MediaRecorder();
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
mediaRecorder.setOutputFile(store_file);
mediaRecorder.prepare();
mediaRecorder.start();
}
private void discardMediaRecorder(){
if (mediaRecorder != null)
mediaRecorder.release();
}
private void stopRecording() {
if (mediaRecorder != null)
mediaRecorder.stop();
}
private void startPlayBack() throws IOException {
discardMediaPlayer();
mediaPlayer = new MediaPlayer();
mediaPlayer.setDataSource(store_file);
mediaPlayer.prepare();
mediaPlayer.start();
}
private void discardMediaPlayer() {
if (mediaPlayer != null)
{
try{
mediaPlayer.release();
}catch (Exception e) {
e.printStackTrace();
}
}
}
private void stopPlayBack() {
if (mediaPlayer != null)
mediaPlayer.stop();
}
}
//Dialog.xml
<?xml version="1.0" encoding="utf-8"?>
<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:orientation="vertical"
android:clickable="true">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/record"
android:id="#+id/imageView" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Start"
android:id="#+id/Startbtn"
android:layout_marginLeft="67dp"
android:layout_marginStart="67dp"
android:onClick="onButtonClick"
android:layout_below="#+id/imageView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="70dp" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Stop"
android:id="#+id/Stopbtn"
android:layout_marginLeft="59dp"
android:layout_marginStart="59dp"
android:layout_alignTop="#+id/Startbtn"
android:layout_toRightOf="#+id/Startbtn"
android:layout_toEndOf="#+id/Startbtn"
android:onClick="onButtonClick"
android:clickable="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="PlayBlack"
android:id="#+id/PlayBackbtn"
android:onClick="onButtonClick"
android:clickable="true"
android:layout_centerVertical="true"
android:layout_alignLeft="#+id/Startbtn"
android:layout_alignStart="#+id/Startbtn" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="StopPlaying"
android:id="#+id/StopPlayingbtn"
android:onClick="onButtonClick"
android:nestedScrollingEnabled="true"
android:clickable="true"
android:layout_centerVertical="true"
android:layout_alignLeft="#+id/Stopbtn"
android:layout_alignStart="#+id/Stopbtn" />
</RelativeLayout>
I am building an app for android, and while setting up my settingActivity and i get this error:
This happens when I start the activity. Before I moved the setContentView(R.layout.activity_setting); to the start of the onCreate() function, the application threw a NullPointerException at b.setOnCLickListener().
Now it throws a RuntimeException at the setContentView(); How do I resolve this?
01-18 14:28:59.116: E/AndroidRuntime(9463): java.lang.RuntimeException: Unable to start activity ComponentInfo{tk.yteditors.london2013/tk.yteditors.london2013.SettingActivity}: java.lang.RuntimeException: Your content must have a ListView whose id attribute is 'android.R.id.list'
01-18 14:28:59.116: E/AndroidRuntime(9463):
at tk.yteditors.london2013.SettingActivity.onCreate(SettingActivity.java:27)
Java code:
package tk.yteditors.london2013;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Random;
import android.annotation.TargetApi;
import android.app.Dialog;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceActivity;
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.Toast;
public class SettingActivity extends PreferenceActivity{
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setupActionBar();
setContentView(R.layout.activity_setting);
Button b = (Button) findViewById(R.id.sendAnswers);
b.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View pView) {
sendAnswers();
}
});
}
/**
* Set up the {#link android.app.ActionBar}, if the API is available.
*/
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
private void setupActionBar() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
getActionBar().setDisplayHomeAsUpEnabled(true);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item){
switch(item.getItemId()){
case R.id.MenuSettings:
//boo
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void sendAnswers(){
final Dialog dialog = new Dialog(this);
dialog.setContentView(R.layout.activity_confirm_dialog);
dialog.setTitle("Antwoorden verzenden?");
((Button) dialog.findViewById(R.id.dialogNo)).setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0) {
dialog.dismiss();
}
});
((Button) dialog.findViewById(R.id.dialogYes)).setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
EditText edit = (EditText) dialog.findViewById(R.id.sendAnswers);
packHTML(edit.getText().toString());
}
});
}
public void packHTML(String name){
try {
String fileDir = "/sdcard/LondonAnswers";
File dir = new File(fileDir);
dir.mkdirs();
String fileName = name +new Random().nextLong() +".html";
File file = new File(dir, fileName);
FileWriter fw = new FileWriter(file, false);
fw.append("<html>\n");
fw.append("<head><title>" +name +"'s antwoorden</title></head>\n");
fw.append("<body>\n");
fw.append("<h1>" +name +"'s antwoorden</h1>\n");
fw.append("</body>\n");
fw.append("</html>");
fw.close();
Intent intent = new Intent(this, MainActivity.class);
intent.putExtra("webAdress", "file://" +fileDir +fileName);
startActivity(intent);
} catch (IOException e) {
Toast t = new Toast(this);
t.setText("Er is iets mis gegaan tijdens het maken van het bestand");
t.setDuration(Toast.LENGTH_SHORT);
t.show();
e.printStackTrace();
}
}
}
xml:
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/scrollView1"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Antwoorden"
android:textAppearance="?android:attr/textAppearanceLarge" />
<Button
android:id="#+id/sendAnswers"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Verzend antwoorden" />
<Button
android:id="#+id/removeAnswers"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Verwijder antwoorden" />
<Button
android:id="#+id/answersNYI"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="NYI" />
</LinearLayout>
</ScrollView>
PreferenceActivity is-a ListActivity, and a ListActivity requires a layout which has a ListView with id #android:id/list. This is also shown in the exception you posted:
Your content must have a ListView whose id attribute is 'android.R.id.list'
Now, it seems that your code doesn't appear to be that of a regular Android preferences activity. Therefore you should change the extends PreferencesActivity to just extends Activity.