To debug, I tried to migrate to a blank activity still it shows the same error. Can't understand why!
So i have that error:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: thingtranslator2.jalle.com.thingtranslator2, PID: 14918
java.lang.IllegalStateException: Could not execute method for android:onClick
java.lang.IllegalStateException: Could not execute method for android:onClick
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:390)
at android.view.View.performClick(View.java:6256)
at android.view.View$PerformClick.run(View.java:24704)
at android.os.Handler.handleCallback(Handler.java:789)
at android.os.Handler.dispatchMessage(Handler.java:98)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6590)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:385)
at android.view.View.performClick(View.java:6256)
at android.view.View$PerformClick.run(View.java:24704)
at android.os.Handler.handleCallback(Handler.java:789)
at android.os.Handler.dispatchMessage(Handler.java:98)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6590)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
Caused by: android.os.FileUriExposedException: file:///storage/emulated/0/Android/data/thingtranslator2.jalle.com.thingtranslator2/cache/tempImage exposed beyond app through ClipData.Item.getUri()
at android.os.StrictMode.onFileUriExposed(StrictMode.java:1958)
at android.net.Uri.checkFileUriExposed(Uri.java:2357)
at android.content.ClipData.prepareToLeaveProcess(ClipData.java:941)
at android.content.Intent.prepareToLeaveProcess(Intent.java:9735)
at android.content.Intent.prepareToLeaveProcess(Intent.java:9741)
at android.content.Intent.prepareToLeaveProcess(Intent.java:9720)
at android.app.Instrumentation.execStartActivity(Instrumentation.java:1618)
at android.app.Activity.startActivityForResult(Activity.java:4482)
at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:767)
at android.app.Activity.startActivityForResult(Activity.java:4440)
at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:754)
at thingtranslator2.jalle.com.thingtranslator2.MainActivity.getImage(MainActivity.java:157)
at java.lang.reflect.Method.invoke(Native Method)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:385)
at android.view.View.performClick(View.java:6256)
at android.view.View$PerformClick.run(View.java:24704)
at android.os.Handler.handleCallback(Handler.java:789)
at android.os.Handler.dispatchMessage(Handler.java:98)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6590)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
And this is my MainActivity code :
package thingtranslator2.jalle.com.thingtranslator2;
import android.app.ProgressDialog;
import android.content.ContextWrapper;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.speech.tts.TextToSpeech;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.pixplicity.easyprefs.library.Prefs;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import thingtranslator2.jalle.com.thingtranslator2.Rest.ApiInterface;
import thingtranslator2.jalle.com.thingtranslator2.Rest.Translation;
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
public
#BindView(R.id.txtTranslation)
TextView txtTranslation;
public
#BindView(R.id.spinner)
Spinner spinner;
public
#BindView(R.id.imgPhoto)
ImageButton imgPhoto;
public
#BindView(R.id.imgSpeaker)
ImageButton btnSpeaker;
public Boolean speakerOn, firstRun;
public TextToSpeech tts;
public List<String> languages = new ArrayList<String>();
public ArrayList<Language> languageList = new ArrayList<Language>();
public ArrayAdapter<Language> spinnerArrayAdapter;
public Language selectedLanguage;
public static final int PICK_IMAGE_ID = 234; // the number doesn't matter
thingtranslator2.jalle.com.thingtranslator2.Tools.MarshMallowPermission marshMallowPermission = new thingtranslator2.jalle.com.thingtranslator2.Tools.MarshMallowPermission(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
ButterKnife.bind(this);
btnSpeaker = (ImageButton)findViewById(R.id.imgSpeaker);
imgPhoto = (ImageButton)findViewById(R.id.imgPhoto);
spinner = (Spinner)findViewById(R.id.spinner);
txtTranslation = (TextView)findViewById(R.id.txtTranslation);
//init our Shared preferences helper
new Prefs.Builder()
.setContext(this)
.setMode(ContextWrapper.MODE_PRIVATE)
.setPrefsName(getPackageName())
.setUseDefaultSharedPreference(true)
.build();
// Prefs.clear();
firstRun = Prefs.getBoolean("firstRun", true);
spinner.setOnItemSelectedListener(this);
tts = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if (status != TextToSpeech.ERROR) {
fillSpinner();
}
}
});
if (firstRun) {
Prefs.putBoolean("firstRun", false);
Prefs.putBoolean("speakerOn", true);
Prefs.putString("langCode", "bs");
}
setSpeaker();
}
private void setSpeaker() {
int id = Prefs.getBoolean("speakerOn", false) ? R.drawable.ic_volume : R.drawable.ic_volume_off;
btnSpeaker.setImageBitmap(BitmapFactory.decodeResource(getResources(), id));
}
public void ToogleSpeaker(View v) {
Prefs.putBoolean("speakerOn", !Prefs.getBoolean("speakerOn", false));
setSpeaker();
Toast.makeText(getApplicationContext(), "Speech " + (Prefs.getBoolean("speakerOn", true) ? "On" : "Off"), Toast.LENGTH_SHORT);
}
private void fillSpinner() {
Iterator itr = tts.getAvailableLanguages().iterator();
while (itr.hasNext()) {
Locale item = (Locale) itr.next();
languageList.add(new Language(item.getDisplayName(), item.getLanguage()));
}
//Sort that array
Collections.sort(languageList, new Comparator<Language>() {
#Override
public int compare(Language o1, Language o2) {
return o1.getlangCode().compareTo(o2.getlangCode());
}
});
spinnerArrayAdapter = new ArrayAdapter<Language>(this, R.layout.spinner_item, languageList);
spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(spinnerArrayAdapter);
String def = Prefs.getString("langCode", "bs");
for (Language lang : languageList) {
if (lang.getlangCode().equals(def)) {
spinner.setSelection(languageList.indexOf(lang));
}
}
}
//Get image from Gallery or Camera
public void getImage(View v) {
if (!marshMallowPermission.checkPermissionForCamera()) {
marshMallowPermission.requestPermissionForCamera();
} else {
if (!marshMallowPermission.checkPermissionForExternalStorage()) {
marshMallowPermission.requestPermissionForExternalStorage();
} else {
Intent chooseImageIntent = thingtranslator2.jalle.com.thingtranslator2.Tools.ImagePicker.getPickImageIntent(getApplicationContext());
startActivityForResult(chooseImageIntent, PICK_IMAGE_ID);
}
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (data == null) return;
switch (requestCode) {
case PICK_IMAGE_ID:
Bitmap bitmap = thingtranslator2.jalle.com.thingtranslator2.Tools.ImagePicker.getImageFromResult(this, resultCode, data);
imgPhoto.setImageBitmap(null);
imgPhoto.setBackground(null);
imgPhoto.setImageBitmap(bitmap);
imgPhoto.invalidate();
imgPhoto.postInvalidate();
File file = null;
try {
file = savebitmap(bitmap, "pic.jpeg");
} catch (IOException e) {
e.printStackTrace();
}
uploadImage(file);
break;
default:
super.onActivityResult(requestCode, resultCode, data);
break;
}
}
private void uploadImage(File file) {
RequestBody body = RequestBody.create(MediaType.parse("image/*"), file);
RequestBody langCode1 = RequestBody.create(MediaType.parse("text/plain"), selectedLanguage.langCode);
final ProgressDialog progress = new ProgressDialog(this);
progress.setMessage("Processing image...");
progress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progress.setIndeterminate(true);
progress.show();
ApiInterface mApiService = ApiInterface.retrofit.create(ApiInterface.class);
Call<Translation> mService = mApiService.upload(body, langCode1);
mService.enqueue(new Callback<Translation>() {
#Override
public void onResponse(Call<Translation> call, Response<Translation> response) {
progress.hide();
Translation result = response.body();
txtTranslation.setText(result.Translation);
txtTranslation.invalidate();
if (Prefs.getBoolean("speakerOn", true)) {
tts.speak(result.Translation, TextToSpeech.QUEUE_FLUSH, null);
}
}
#Override
public void onFailure(Call<Translation> call, Throwable t) {
call.cancel();
progress.hide();
Toast.makeText(getApplicationContext(), "Error: " + t.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
public static File savebitmap(Bitmap bmp, String fName) throws IOException {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 60, bytes);
File f = new File(Environment.getExternalStorageDirectory()
+ File.separator + fName);
f.createNewFile();
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
fo.close();
return f;
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
selectedLanguage = (Language) spinner.getSelectedItem();
// langCode = languages.get(position);
tts.setLanguage(Locale.forLanguageTag(selectedLanguage.langCode));
Prefs.putString("langCode", selectedLanguage.langCode);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
}
activity_main.xml file:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/colorBlack"
android:paddingBottom="8dp"
android:paddingLeft="8dp"
android:paddingRight="8dp"
android:paddingTop="8dp"
tools:context="thingtranslator2.jalle.com.thingtranslator2.MainActivity">
<LinearLayout
android:id="#+id/layout1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:gravity="center_vertical"
android:orientation="horizontal"
android:weightSum="1">
<Spinner
android:id="#+id/spinner"
android:layout_width="100dp"
android:layout_height="match_parent"
android:layout_marginBottom="16dp"
android:layout_weight="0.91"
android:gravity="bottom|end" />
<ImageButton
android:id="#+id/imgSpeaker"
android:layout_width="wrap_content"
android:layout_height="50dp"
android:layout_gravity="end"
android:layout_weight=".10"
android:background="#android:color/transparent"
android:onClick="ToogleSpeaker"
android:scaleType="fitCenter"
app:srcCompat="#drawable/ic_volume"
android:contentDescription="#string/todo" />
</LinearLayout>
<TextView
android:id="#+id/txtTranslation"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/layout1"
android:layout_centerHorizontal="true"
android:layout_marginBottom="16dp"
android:gravity="center_horizontal"
android:onClick="getImage"
android:text="#string/select_image_from_n_gallery_or_take_new_photo"
android:textColor="#android:color/white"
android:textSize="26sp"
tools:text="message" />
<ImageButton
android:id="#+id/imgPhoto"
android:layout_width="fill_parent"
android:layout_height="400dp"
android:layout_alignParentBottom="true"
android:layout_alignParentStart="true"
android:layout_below="#id/txtTranslation"
android:background="#drawable/takephoto"
android:onClick="getImage" />
</RelativeLayout>
AndroidMnifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="thingtranslator2.jalle.com.thingtranslator2">
<uses-feature android:name="android.hardware.camera" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-feature android:name="android.hardware.camera.autofocus" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity" >
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Related
Image is showing nothing not even the image I chose as default no error nothing just the image cannot be loaded I granted internet permission still this is happening plz help
No error is there in logcat.
App launches everything is fine but the image wont load i tried waiting still and the API is working fine......i dunno if its my code or the permission which is causing this...
Java Code
package com.example.meme_share;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.os.StrictMode;
import android.widget.ImageView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.bumptech.glide.Glide;
import org.json.JSONException;
import org.json.JSONObject;
public class MainActivity extends AppCompatActivity {
ImageView i;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageView i = findViewById(R.id.imageView);
}
public void loadmeme() {
RequestQueue a = Volley.newRequestQueue(this);
String url = "https://meme-api.herokuapp.com/gimme";
JsonObjectRequest b = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
String u = null;
try {
u = response.getString("url");
System.out.println("Raunak"+u);
} catch (JSONException e) {
e.printStackTrace();
}
System.out.println("Raunak"+u);
Glide.with(MainActivity.this).load(u).into(i);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, "Error occurred", Toast.LENGTH_SHORT).show();
}
});
}
}
XML
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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=".MainActivity">
<Button
android:id="#+id/button2"
android:layout_width="182dp"
android:layout_height="71dp"
android:layout_marginTop="134dp"
android:text="Next"
app:backgroundTint="#android:color/tertiary_text_light"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.93"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/imageView"
app:layout_constraintVertical_bias="1.0" />
<ImageView
android:id="#+id/imageView"
android:layout_width="415dp"
android:layout_height="538dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.06"
tools:srcCompat="#drawable/ic_launcher_background" />
<Button
android:id="#+id/button"
android:layout_width="182dp"
android:layout_height="71dp"
android:layout_marginTop="134dp"
android:text="Share"
app:backgroundTint="#android:color/tertiary_text_light"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/imageView"
app:layout_constraintVertical_bias="0.956" />
</androidx.constraintlayout.widget.ConstraintLayout>
Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.meme_share">
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/Theme.Meme_Share">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
You have created two ImageView i; variables: first in onCreate methon and second in class scope.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
i = findViewById(R.id.imageView); // < here
}
Besides this problem here are some others:
You don't call loadmeme method anywhere
You don't make network request
ImageView imageView; // 1. Use class scoped imageView
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = findViewById(R.id.imageView);
// 2. Run loadmeme method
loadmeme();
}
public void loadmeme() {
RequestQueue requestQueue = Volley.newRequestQueue(this);
String url = "https://meme-api.herokuapp.com/gimme";
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
String u = null;
try {
u = response.getString("url");
System.out.println("Raunak" + u);
} catch (JSONException e) {
e.printStackTrace();
}
System.out.println("Raunak" + u);
Glide.with(MainActivity.this).load(u).into(imageView);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, "Error occurred", Toast.LENGTH_SHORT).show();
}
});
// 3. Add request to queue
requestQueue.add(jsonObjectRequest);
}
I am a Android beginner, making a simple Service example.
but in a single code getApplicationContext() method behaves differently, Please check comment of MainActivity.
MainActivity.java
package com.avisingh.servicetest;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button alertButton = (Button)findViewById(R.id.alert_btn);
alertButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this); //If i placing here getApplicationContext() method then getting error;
builder.setTitle("Warning");
builder.setMessage("Are you sure to open media played in this app?");
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
startActivity(new Intent(getApplicationContext(),PlayerActivity.class)); // here getApplicationContext() and MainActivity.this both working
}
});
builder.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show(); //getting error here.
}
});
}
}
PlayerActivity.java
package com.avisingh.servicetest;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
public class PlayerActivity extends AppCompatActivity{
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.player_activity);
final Button startBtn = (Button)findViewById(R.id.start_btn);
final Button stopBtn = (Button)findViewById(R.id.stop_btn);
startBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startService(new Intent(getApplicationContext(),MyServices.class));
}
});
stopBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
stopService(new Intent(getApplicationContext(),MyServices.class));
}
});
}
}
MyServices.java
package com.avisingh.servicetest;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.support.annotation.Nullable;
public class MyServices extends Service {
MediaPlayer mediaPlayer;
#Nullable
#Override
public IBinder onBind(Intent intent) {
//return null;
throw new UnsupportedOperationException("Not implemented");
}
#Override
public void onCreate() {
super.onCreate();
mediaPlayer = MediaPlayer.create(getApplicationContext(),R.raw.one_man);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
mediaPlayer.start();
return super.onStartCommand(intent, flags, startId);
}
#Override
public void onDestroy() {
super.onDestroy();
mediaPlayer.stop();
}
}
AndroidManifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.avisingh.servicetest">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".PlayerActivity"/>
<service android:name=".MyServices"/>
</application>
activity_main
<?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"
tools:context="com.avisingh.servicetest.MainActivity">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/alert_btn"
android:layout_centerHorizontal="true"
android:layout_marginTop="40dp"
android:id="#+id/alert_btn"/>
</RelativeLayout>
player_activity
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:text="#string/start_btn"
android:id="#+id/start_btn"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="50dp"
android:text="#string/stop_btn"
android:id="#+id/stop_btn"/>
</RelativeLayout>
Error:
08-14 14:17:58.916 6874-6874/com.avisingh.servicetest E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.avisingh.servicetest, PID: 6874
java.lang.IllegalStateException: You need to use a Theme.AppCompat theme (or descendant) with this activity.
at android.support.v7.app.AppCompatDelegateImplV9.createSubDecor(AppCompatDelegateImplV9.java:359)
at android.support.v7.app.AppCompatDelegateImplV9.ensureSubDecor(AppCompatDelegateImplV9.java:328)
at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:289)
at android.support.v7.app.AppCompatDialog.setContentView(AppCompatDialog.java:83)
at android.support.v7.app.AlertController.installContent(AlertController.java:225)
at android.support.v7.app.AlertDialog.onCreate(AlertDialog.java:257)
at android.app.Dialog.dispatchOnCreate(Dialog.java:373)
at android.app.Dialog.show(Dialog.java:274)
at com.avisingh.servicetest.MainActivity$1.onClick(MainActivity.java:42)
at android.view.View.performClick(View.java:4759)
at android.view.View$PerformClick.run(View.java:19770)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5247)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:912)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:707)
//If i placing here getApplicationContext() method then getting error
Correct. That is because the Application object does not know anything about themes, and your dialog needs a theme based on Theme.AppCompat. Always use your Activity context for creating dialogs.
You may wish to read Dave Smith's awesome blog post on the uses of different types of Context object for more on this.
I am creating a facebook login for my android application. I am getting following below errors which i tried to solve but i can not because i am unable to find solution.
1) Error:(46, 46) error: cannot find symbol method getAccessToken()
2) Error:(41, 55) error: incompatible types: > cannot be converted to FacebookCallback
My activity_main.xml is:
<?xml version="1.0" encoding="utf-8"?>
<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:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#5b9bd5"
tools:context="com.example.ratingapp.ratingapp.MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/info"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:textSize="18sp"
/>
<com.facebook.login.widget.LoginButton
android:id="#+id/login_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
/>
</android.support.constraint.ConstraintLayout>
My MainActivity.java is:
package com.example.ratingapp.ratingapp;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.FacebookSdk;
import com.facebook.accountkit.LoginResult;
import com.facebook.login.LoginManager;
import com.facebook.login.widget.LoginButton;
import java.util.Arrays;
import java.util.List;
import static android.R.attr.data;
public class MainActivity extends AppCompatActivity {
private TextView info;
private LoginButton loginButton;
private CallbackManager callbackManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(this.getApplicationContext());
setContentView(R.layout.activity_main);
callbackManager = CallbackManager.Factory.create();
loginButton = (LoginButton) findViewById(R.id.login_button);
List<String> permissionNeeds = Arrays.asList("user_photos", "email", "user_birthday", "public_profile");
loginButton.setReadPermissions(permissionNeeds);
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
info.setText(
"User ID: "
+ loginResult.getAccessToken().getUserId()
+ "\n" +
"Auth Token: "
+ loginResult.getAccessToken().getToken()
);
}
#Override
public void onCancel() {
info.setText("Login attempt canceled.");
}
#Override
public void onError(FacebookException exception) {
info.setText("Login attempt failed.");
}
});
}
}
Please help me solve these errors what i am doing wrong in this code.
Please alsoc check my AndroidManifest.xml incase i put a wrong facebook library.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.ratingapp.ratingapp">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER"
/>
</intent-filter>
</activity>
<activity android:name="com.facebook.FacebookActivity"
android:configChanges=
"keyboard|keyboardHidden|screenLayout|screenSize|orientation"
android:theme="#android:style/Theme.Translucent.NoTitleBar"
android:label="#string/app_name" />
<meta-data android:name="com.facebook.sdk.ApplicationId"
android:value="#string/facebook_app_id"/>
</application>
<uses-permission android:name="android.permission.INTERNET"/>
/manifest>
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>()
{
#Override
public void onSuccess (final LoginResult loginResult)
{
GraphRequest request = GraphRequest.newMeRequest(loginResult.getAccessToken(), new GraphRequest.GraphJSONObjectCallback()
{
#Override
public void onCompleted (JSONObject object, GraphResponse response)
{
try
{
String id = response.getJSONObject().getString("id");
((InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(passwordEditText.getWindowToken(), 0);
if (connect())
{
/*ENTER*/
}
else
{
Toast.makeText(getApplicationContext(), textProblemConnecting(), Toast.LENGTH_LONG).show();
}
}
catch (JSONException e)
{
e.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("YOUR FIELDS");
request.setParameters(parameters);
request.executeAsync();
}
#Override
public void onCancel ()
{
}
#Override
public void onError (FacebookException e)
{
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "first_name, email, id, last_name, birthday, locale");
request.setParameters(parameters);
request.executeAsync();
I just started android programming a couple of days ago. I'm trying to integrate google plus login into my App. I followed the tutorial here. When I tried to deploy my app, I get an error message saying -
Unfortunately OAuthTest has stopped.
The logcat shows the following error:
10-10 10:31:37.239 32048-32048/agility.oauthtest D/dalvikvm﹕ Late-enabling CheckJNI
10-10 10:31:37.622 32048-32048/agility.oauthtest D/AndroidRuntime﹕ Shutting down VM
10-10 10:31:37.622 32048-32048/agility.oauthtest W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x416a8d40)
10-10 10:31:37.627 32048-32048/agility.oauthtest E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: agility.oauthtest, PID: 32048
java.lang.RuntimeException: Unable to start activity ComponentInfo{agility.oauthtest/agility.oauthtest.login}: java.lang.NullPointerException: Null options are not permitted for this Api
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2198)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2257)
at android.app.ActivityThread.access$800(ActivityThread.java:139)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1210)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5086)
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)
Caused by: java.lang.NullPointerException: Null options are not permitted for this Api
at com.google.android.gms.internal.fq.b(Unknown Source)
at com.google.android.gms.common.api.GoogleApiClient$Builder.addApi(Unknown Source)
at agility.oauthtest.login.onCreate(login.java:83)
at android.app.Activity.performCreate(Activity.java:5248)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1110)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2162)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2257)
at android.app.ActivityThread.access$800(ActivityThread.java:139)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1210)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5086)
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)
My code is as follows
Activity_login.xml
<LinearLayout 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:padding="16dp"
tools:context=".login" >
<LinearLayout
android:id="#+id/llProfile"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="20dp"
android:orientation="horizontal"
android:weightSum="3"
android:visibility="gone">
<ImageView
android:id="#+id/imgProfilePic"
android:layout_width="80dp"
android:layout_height="wrap_content"
android:layout_weight="1"/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:orientation="vertical"
android:layout_weight="2" >
<TextView
android:id="#+id/txtName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="5dp"
android:textSize="20dp" />
<TextView
android:id="#+id/txtEmail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="5dp"
android:textSize="18dp" />
</LinearLayout>
</LinearLayout>
<com.google.android.gms.common.SignInButton
android:id="#+id/btn_sign_in"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="20dp"/>
<Button
android:id="#+id/btn_sign_out"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/btn_logout_from_google"
android:visibility="gone"
android:layout_marginBottom="10dp"/>
<Button
android:id="#+id/btn_revoke_access"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/btn_revoke_access"
android:visibility="gone" />
</LinearLayout>
login.java
package agility.oauthtest;
import android.app.Activity;
import android.content.Intent;
import android.content.IntentSender.SendIntentException;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.SignInButton;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;
import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.plus.Plus;
import com.google.android.gms.plus.model.people.Person;
import java.io.InputStream;
public class login extends Activity implements OnClickListener,
ConnectionCallbacks, OnConnectionFailedListener {
private static final int RC_SIGN_IN = 0;
// Logcat tag
private static final String TAG = "Login";
// Profile pic image size in pixels
private static final int PROFILE_PIC_SIZE = 400;
// Google client to interact with Google API
private GoogleApiClient mGoogleApiClient;
/**
* A flag indicating that a PendingIntent is in progress and prevents us
* from starting further intents.
*/
private boolean mIntentInProgress;
private boolean mSignInClicked;
private ConnectionResult mConnectionResult;
private SignInButton btnSignIn;
private Button btnSignOut, btnRevokeAccess;
private ImageView imgProfilePic;
private TextView txtName, txtEmail;
private LinearLayout llProfileLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
btnSignIn = (SignInButton) findViewById(R.id.btn_sign_in);
btnSignOut = (Button) findViewById(R.id.btn_sign_out);
btnRevokeAccess = (Button) findViewById(R.id.btn_revoke_access);
imgProfilePic = (ImageView) findViewById(R.id.imgProfilePic);
txtName = (TextView) findViewById(R.id.txtName);
txtEmail = (TextView) findViewById(R.id.txtEmail);
llProfileLayout = (LinearLayout) findViewById(R.id.llProfile);
// Button click listeners
btnSignIn.setOnClickListener(this);
btnSignOut.setOnClickListener(this);
btnRevokeAccess.setOnClickListener(this);
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this).addApi(Plus.API, null)
.addScope(Plus.SCOPE_PLUS_LOGIN).build();
}
protected void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
protected void onStop() {
super.onStop();
if (mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
}
}
/**
* Method to resolve any signin errors
* */
private void resolveSignInError() {
if (mConnectionResult.hasResolution()) {
try {
mIntentInProgress = true;
mConnectionResult.startResolutionForResult(this, RC_SIGN_IN);
} catch (SendIntentException e) {
mIntentInProgress = false;
mGoogleApiClient.connect();
}
}
}
#Override
public void onConnectionFailed(ConnectionResult result) {
if (!result.hasResolution()) {
GooglePlayServicesUtil.getErrorDialog(result.getErrorCode(), this,
0).show();
return;
}
if (!mIntentInProgress) {
// Store the ConnectionResult for later usage
mConnectionResult = result;
if (mSignInClicked) {
// The user has already clicked 'sign-in' so we attempt to
// resolve all
// errors until the user is signed in, or they cancel.
resolveSignInError();
}
}
}
#Override
protected void onActivityResult(int requestCode, int responseCode,
Intent intent) {
if (requestCode == RC_SIGN_IN) {
if (responseCode != RESULT_OK) {
mSignInClicked = false;
}
mIntentInProgress = false;
if (!mGoogleApiClient.isConnecting()) {
mGoogleApiClient.connect();
}
}
}
#Override
public void onConnected(Bundle arg0) {
mSignInClicked = false;
Toast.makeText(this, "User is connected!", Toast.LENGTH_LONG).show();
// Get user's information
getProfileInformation();
// Update the UI after signin
updateUI(true);
}
/**
* Updating the UI, showing/hiding buttons and profile layout
* */
private void updateUI(boolean isSignedIn) {
if (isSignedIn) {
btnSignIn.setVisibility(View.GONE);
btnSignOut.setVisibility(View.VISIBLE);
btnRevokeAccess.setVisibility(View.VISIBLE);
llProfileLayout.setVisibility(View.VISIBLE);
} else {
btnSignIn.setVisibility(View.VISIBLE);
btnSignOut.setVisibility(View.GONE);
btnRevokeAccess.setVisibility(View.GONE);
llProfileLayout.setVisibility(View.GONE);
}
}
/**
* Fetching user's information name, email, profile pic
* */
private void getProfileInformation() {
try {
if (Plus.PeopleApi.getCurrentPerson(mGoogleApiClient) != null) {
Person currentPerson = Plus.PeopleApi
.getCurrentPerson(mGoogleApiClient);
String personName = currentPerson.getDisplayName();
String personPhotoUrl = currentPerson.getImage().getUrl();
String personGooglePlusProfile = currentPerson.getUrl();
String email = Plus.AccountApi.getAccountName(mGoogleApiClient);
Log.e(TAG, "Name: " + personName + ", plusProfile: "
+ personGooglePlusProfile + ", email: " + email
+ ", Image: " + personPhotoUrl);
txtName.setText(personName);
txtEmail.setText(email);
// by default the profile url gives 50x50 px image only
// we can replace the value with whatever dimension we want by
// replacing sz=X
personPhotoUrl = personPhotoUrl.substring(0,
personPhotoUrl.length() - 2)
+ PROFILE_PIC_SIZE;
new LoadProfileImage(imgProfilePic).execute(personPhotoUrl);
} else {
Toast.makeText(getApplicationContext(),
"Person information is null", Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onConnectionSuspended(int arg0) {
mGoogleApiClient.connect();
updateUI(false);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.login, menu);
return true;
}
/**
* Button on click listener
* */
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_sign_in:
// Signin button clicked
signInWithGplus();
break;
case R.id.btn_sign_out:
// Signout button clicked
signOutFromGplus();
break;
case R.id.btn_revoke_access:
// Revoke access button clicked
revokeGplusAccess();
break;
}
}
/**
* Sign-in into google
* */
private void signInWithGplus() {
if (!mGoogleApiClient.isConnecting()) {
mSignInClicked = true;
resolveSignInError();
}
}
/**
* Sign-out from google
* */
private void signOutFromGplus() {
if (mGoogleApiClient.isConnected()) {
Plus.AccountApi.clearDefaultAccount(mGoogleApiClient);
mGoogleApiClient.disconnect();
mGoogleApiClient.connect();
updateUI(false);
}
}
/**
* Revoking access from google
* */
private void revokeGplusAccess() {
if (mGoogleApiClient.isConnected()) {
Plus.AccountApi.clearDefaultAccount(mGoogleApiClient);
Plus.AccountApi.revokeAccessAndDisconnect(mGoogleApiClient)
.setResultCallback(new ResultCallback<Status>() {
#Override
public void onResult(Status arg0) {
Log.e(TAG, "User access revoked!");
mGoogleApiClient.connect();
updateUI(false);
}
});
}
}
/**
* Background Async task to load user profile picture from url
* */
private class LoadProfileImage extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public LoadProfileImage(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="agility.oauthtest" >
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.USE_CREDENTIALS" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".login"
android:label="#string/app_name" >
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
What I already did -
Cleaned the Application. Rebuilt it.
What I am still confused about.
I created the Client ID in Google API Console, but I've never used it anywhere in the code. And the tutorial seems to be working for many other people.
If anyone could help me here, it would be awesome. Thanks.
pass a single parameter in addApi as .addApi(Plus.API),i.e.
Change
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this).addApi(Plus.API, null)
.addScope(Plus.SCOPE_PLUS_LOGIN).build();
to
mGoogleApiClient = new GoogleApiClient.Builder(this,this,this)
.addApi(Plus.API)
.addScope(Plus.SCOPE_PLUS_LOGIN)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
as your Logcat shows java.lang.NullPointerException: Null options are not permitted for this Api
hence try this code:
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(Plus.API)
.addScope(Plus.SCOPE_PLUS_LOGIN)
.build();
I'm using tesseract-android-tools (pre-built lib) for ANPR. But having problem when the image background is worse. Can anybody suggest how can I focus/get rectangular area of/from image taken from camera. Despite of searching the forum I'm unable to get a working example on this.
Here is my code:~
1) AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.ocrtest"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="18" />
<uses-feature android:name="android.hardware.camera" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.ocrtest.OcrActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
2) main.xml (layout)
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/scrollView1"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="10dp" >
<ImageView
android:id="#+id/image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:contentDescription="Output"
android:src="#drawable/ic_launcher" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="center"
>
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Take Pic" />
</LinearLayout>
<TextView
android:id="#+id/field"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="N/A" />
</LinearLayout>
</ScrollView>
3) OcrActivity.java
import java.io.File;
import java.io.IOException;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.googlecode.tesseract.android.TessBaseAPI;
public class OcrActivity extends Activity implements View.OnClickListener {
protected Button _button;
protected ImageView _image;
protected TextView _field;
protected String _path;
protected boolean _taken;
protected static final String PHOTO_TAKEN = "photo_taken";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
_image = (ImageView) findViewById(R.id.image);
_field = (TextView) findViewById(R.id.field);
_button = (Button) findViewById(R.id.button);
_button.setOnClickListener(this);
File f = new File(Environment.getExternalStorageDirectory()
+ "/tessaract_languages");
if (f.isDirectory()) {
File imgDirectory = new File(
Environment.getExternalStorageDirectory() + "/images/");
imgDirectory.mkdirs();
} else {
Toast.makeText(getApplicationContext(),
"OCR library files missing.", Toast.LENGTH_LONG).show();
finish();
}
_path = Environment.getExternalStorageDirectory()
+ "/images/make_machine_example.jpg";
}
#Override
public void onClick(View v) {
switch(v.getId()) {
case R.id.button:
Log.i("MakeMachine", "ButtonClickHandler.onClick()");
startCameraActivity();
break;
}
}
protected void startCameraActivity() {
Log.i("MakeMachine", "startCameraActivity()");
File file = new File(_path);
Uri outputFileUri = Uri.fromFile(file);
Intent intent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(intent, 0);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.i("MakeMachine", "resultCode: " + resultCode);
switch (resultCode) {
case 0:
Log.i("MakeMachine", "User cancelled");
break;
case -1:
try {
onPhotoTaken();
} catch (IOException e) {
e.printStackTrace();
}
break;
}
}
protected void onPhotoTaken() throws IOException {
_taken = true;
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 4;
Bitmap bitmap = BitmapFactory.decodeFile(_path, options);
_image.setImageBitmap(bitmap);
// _field.setVisibility(View.GONE);
ExifInterface exif = new ExifInterface(_path);
int exifOrientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION,ExifInterface.ORIENTATION_NORMAL);
int rotate = 0;
switch (exifOrientation) {
case ExifInterface.ORIENTATION_ROTATE_90:
rotate = 90;
break;
case ExifInterface.ORIENTATION_ROTATE_180:
rotate = 180;
break;
case ExifInterface.ORIENTATION_ROTATE_270:
rotate = 270;
break;
}
if (rotate != 0) {
int w = bitmap.getWidth();
int h = bitmap.getHeight();
Matrix mtx = new Matrix();
mtx.preRotate(rotate);
bitmap = Bitmap.createBitmap(bitmap, 0, 0, w, h, mtx, false);
bitmap = bitmap.copy(Bitmap.Config.ARGB_8888, true);
} else {
bitmap = bitmap.copy(Bitmap.Config.ARGB_8888, true);
}
TessBaseAPI baseApi = new TessBaseAPI();
baseApi.init(Environment.getExternalStorageDirectory()+ "/tessaract_languages/", "eng");
baseApi.setImage(bitmap);
String recognizedText = baseApi.getUTF8Text();
System.out.println(recognizedText);
_field.setText(recognizedText);
baseApi.end();
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
Log.i("MakeMachine", "onRestoreInstanceState()");
if (savedInstanceState.getBoolean(OcrActivity.PHOTO_TAKEN)) {
try {
onPhotoTaken();
} catch (IOException e) {
e.printStackTrace();
}
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
outState.putBoolean(OcrActivity.PHOTO_TAKEN, _taken);
}
}