App crashes while executing the textView command - java

My android app was supposed to send an image to a local java server via sockets and after processing the image the result has to be sent to the app again and i am supposed to display it in the text view.I have successfully received the result but while i am trying to display the result in the text view the app crashes showing the following error.
Error: java.lang.NullPointerException: Attempt to invoke virtual method 'void java.text.BreakIterator.setText(java.lang.String)' on a null object reference
I am new to Android programming.I have tried many things but couldnt solve it.Please help me!
Thanks in advance!
Code: Main Activity
package com.example.image1;
import android.app.Activity;
import android.app.MediaRouteButton;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Base64;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.Nullable;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.text.BreakIterator;
import java.util.Objects;
public class MainActivity extends Activity {
/** Called when the activity is first created. */
private static final int SELECT_PICTURE = 1;
private static final int GET_PICTURE =1 ;
private PrintWriter printwriter;
public static String selectedImagePath;
public static String selectedImageUri;
private ImageView img;
public static String st;
TextView status1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
System.out.println("34");
img = (ImageView) findViewById(R.id.ivPic);
System.out.println("36");
Button send = (Button) findViewById(R.id.bSend);
//status = (TextView) findViewById(R.id.tvStatus);
status1 = (TextView) findViewById(R.id.result);
((Button) findViewById(R.id.bBrowse))
.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
System.out.println("40");
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(
Intent.createChooser(intent, "Select Picture"),
SELECT_PICTURE);
System.out.println("47");
}
});
;
System.out.println("51");
//status1.setText("fjfjf");
send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
//status1.setText("fjfjf");
new SendImageTask().execute();
//final TextView status1 = (TextView) findViewById(R.id.result);
//status1.setText(s);
}
});
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_PICTURE) {
Uri selectedImageUri = data.getData();
selectedImagePath = getPath(selectedImageUri);
TextView path = (TextView) findViewById(R.id.tvPath);
path.setText("Image Path : " + selectedImagePath);
img.setImageURI(selectedImageUri);
}
}
}
public String getPath(Uri uri) {
String[] projection = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(projection[0]);
String filePath = cursor.getString(columnIndex);
cursor.close();
return filePath;
}
}
SendImageTask code
package com.example.image1;
import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Base64;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.text.BreakIterator;
class SendImageTask extends AsyncTask<Void, Void, String> {
private PrintWriter printwriter;
private Bitmap IOUtils;
private BreakIterator status1;
private static String st;
#SuppressLint("WrongThread")
#Override
protected String doInBackground(Void... voids) {
Socket sock;
try {
sock = new Socket("192.168.43.120", 8000);
System.out.println("Connecting...");
System.out.println("Sending...");
String s = getFileToByte(MainActivity.selectedImagePath);
System.out.println(s);
printwriter = new PrintWriter(sock.getOutputStream(), true);
printwriter.write(String.valueOf(s)); // write the message to output stream
printwriter.flush();
printwriter.close();
sock.close();
try {
System.out.println("Another socket");
Socket sock1 = new Socket("192.168.43.120", 6000);
System.out.println("Connecting1...");
InputStreamReader streamReader = new InputStreamReader(sock1.getInputStream());
BufferedReader reader = new BufferedReader(streamReader);
st = reader.readLine();
System.out.println(st);
System.out.println("ascscasc");
sock1.close();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return st;
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return st;
}
protected void onPostExecute(String st){
System.out.println("asasdcwdcwdc");
System.out.println(st);
status1.setText(String.valueOf(st));
}
public static String getFileToByte(String filePath){
Bitmap bmp = null;
ByteArrayOutputStream bos = null;
byte[] bt = null;
String encodeString = null;
try{
bmp = BitmapFactory.decodeFile(filePath);
bos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, bos);
bt = bos.toByteArray();
encodeString = Base64.encodeToString(bt, Base64.DEFAULT);
}
catch (Exception e){
e.printStackTrace();
}
String str1=encodeString.replaceAll("[\r\n]+", " ");
str1 = str1.replaceAll("\\s+","");
return "data:image/jpeg;base64,"+str1+"/n";
}
}
First my app was crashing because i was doing the textView operation in the doInBackground method and then after only i learnt that ui operations cant be done there. So then i executed those commands in onPostExecute method.But still my app is crashing saying NullPointerException.I will also include the logcat here.Thanks in advance.
Logcat:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.image1, PID: 20241
java.lang.NullPointerException: Attempt to invoke virtual method 'void java.text.BreakIterator.setText(java.lang.String)' on a null object reference
at com.example.image1.SendImageTask.onPostExecute(SendImageTask.java:147)
at com.example.image1.SendImageTask.onPostExecute(SendImageTask.java:19)
at android.os.AsyncTask.finish(AsyncTask.java:667)
at android.os.AsyncTask.-wrap1(AsyncTask.java)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:684)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:186)
at android.app.ActivityThread.main(ActivityThread.java:6509)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:914)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:804)
I/Process: Sending signal. PID: 20241 SIG: 9

You need to initialize your BreakIterator object status1 otherwise it would be null.
I've not used BreakIterator, but a quick look at the docs shows that this is how you get an instance.
BreakIterator status1 = BreakIterator.getWordInstance();
Bottom line is to initialize it before using it.

Related

Send an image and other string parameters to server using HttpURLConnection and Base64

I am trying to send an image and some string values from android to a php script using HttpURLConnection. I have successfully done so with strings, but can't seem to get it right with the image. I am using Base64 (android.util.Base64) to convert my image to a string to send it. Now, I have a separate HttpParse.java file I use to send all my info to the server, and I think that is where the change needs to be made to allow the image, but I'm not sure, (I am newer to java/android development). I've researched several similar questions, but they aren't fully clicking for me for what I'm doing wrong. Also, I have tested that I am successfully converting the image to a string. Here is my code:
EDIT I got a little farther... After testing, I am getting the issue because the three variables I try to get with getArguments() are coming back as null... But, I can't figure out how to get them to come through successfully... I added the code for how I start my fragment and how I try to get my bundle
My fragment start:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_units);
Intent intent = getIntent();
LexaUser = intent.getStringExtra("UserName");
ReadOnly = intent.getStringExtra("ReadOnly");
Password = intent.getStringExtra("Password");
QA = intent.getStringExtra("QA");
SearchValue = intent.getStringExtra("SearchInput");
bottomNavigation = (BottomNavigationView)findViewById(R.id.bottom_navigation);
bottomNavigation.inflateMenu(R.menu.bottom_menu);
fragmentManager = getSupportFragmentManager();
bottomNavigation.getMenu().getItem(0).setChecked(true);
UnitDetailsHeader = findViewById(R.id.UnitDetailsViewTitle);
UnitDetailsHeader.setText(SearchValue);
UnitSizeText = findViewById(R.id.UnitSize);
UnitStatusText = findViewById(R.id.UnitStatus);
if (SearchValue.contains("-")) {
getUnitDetails(SearchValue, LexaUser);
} else {
getSiblings();
}
bottomNavigation.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
int id = item.getItemId();
switch (id){
case R.id.action_search:
fragment = new NewUnitStatusFragment();
break;
case R.id.action_cart:
fragment = new PendingUnitStatusFragment();
break;
case R.id.action_hot_deals:
fragment = new FinalUnitStatusFragment();
break;
case R.id.action_siblings:
fragment = new SiblingUnitFragment();
break;
}
Bundle connBundle = new Bundle();
connBundle.putString("SearchValue", SearchValue);
connBundle.putString("LexaUser", LexaUser);
connBundle.putString("Password", Password);
connBundle.putString("QA", QA);
fragment.setArguments(connBundle);
final FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.replace(R.id.main_container, fragment).commit();
return true;
}
});
}
And where I try to get my arguments: (I originally had in onCreateView but then tried to move it to onCreate. But the behavior was the same)
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
SearchValue = getArguments().getString("SearchValue");
LexaUser = getArguments().getString("LexaUser");
Password = getArguments().getString("Password");
}
}
My fragment where I get the image and send my data:
package [my_package];
import android.Manifest;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.SpinnerAdapter;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import android.util.Base64;
import java.util.HashMap;
import static android.app.Activity.RESULT_OK;
public class NewUnitStatusFragment extends Fragment {
Context newUnitStatusContext;
Activity newUnitStatusActivity;
Intent cameraIntent;
ProgressDialog progressDialog;
String ReadOnly;
String LexaUser;
String Password;
String SearchValue;
String finalResultNewUnitStatus;
String HttpURLNewUnitStatus = "https://[path/to/file]/insertNewUnitStatus.php";
HashMap<String, String> hashMapNewUnitStatus = new HashMap<>();
HttpParse httpParse = new HttpParse();
Spinner statusSpinner;
Spinner generalCauseSpinner;
EditText newUSComment;
Button addPhotoBtn;
ImageView newUnitStatusImage;
Button addNewUnitStatus;
String newUnitStatus;
String generalCause;
String newUnitStatusComment;
String newUnitStatusPhoto;
String message;
private static final int PICK_FROM_GALLERY = 1;
public NewUnitStatusFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_newunitstatus, container, false);
newUnitStatusContext = getContext();
newUnitStatusActivity = getActivity();
statusSpinner = view.findViewById(R.id.Status);
generalCauseSpinner = view.findViewById(R.id.GeneralCause);
newUSComment = view.findViewById(R.id.NewComment);
newUnitStatusImage = view.findViewById(R.id.AddPhoto);
addPhotoBtn = view.findViewById(R.id.AddPhotosLabel);
addNewUnitStatus = view.findViewById(R.id.addBtnNewUnitStatus);
ArrayAdapter<CharSequence> statusSpinnerAdapter = ArrayAdapter.createFromResource(newUnitStatusContext,
R.array.new_unit_status_array, android.R.layout.simple_spinner_item);
statusSpinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
statusSpinner.setAdapter(statusSpinnerAdapter);
newUnitStatus = statusSpinner.getSelectedItem().toString();
ArrayAdapter<CharSequence> generalCauseSpinnerAdapter = ArrayAdapter.createFromResource(newUnitStatusContext,
R.array.status_general_cause_array, android.R.layout.simple_spinner_item);
generalCauseSpinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
generalCauseSpinner.setAdapter(generalCauseSpinnerAdapter);
generalCause = generalCauseSpinner.getSelectedItem().toString();
addPhotoBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startGallery();
}
});
// Set a click listener for the text view
addNewUnitStatus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
newUnitStatus = statusSpinner.toString();
generalCause = generalCauseSpinner.toString();
newUnitStatusComment = newUSComment.toString();
if (getArguments() != null) {
SearchValue = getArguments().getString("SearchValue");
LexaUser = getArguments().getString("LexaUser");
Password = getArguments().getString("Password");
}
addNewUnitStatus(SearchValue, newUnitStatus, generalCause, newUnitStatusComment, newUnitStatusPhoto, LexaUser, Password);
}
});
return view;
}
private void startGallery() {
cameraIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
cameraIntent.setType("image/*");
cameraIntent.setAction(Intent.ACTION_GET_CONTENT);
if (cameraIntent.resolveActivity(getActivity().getPackageManager()) != null) {
startActivityForResult(cameraIntent, 1000);
} else {
Toast.makeText(newUnitStatusContext, "Error: " + cameraIntent + " - cameraIntent.resolveActivity(getActivity().getPackageManager()) = null", Toast.LENGTH_LONG).show();
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
//super method removed
if (resultCode == RESULT_OK) {
if (requestCode == 1000) {
Uri returnUri = data.getData();
try {
Bitmap bitmapImage = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), returnUri);
newUnitStatusImage.setImageBitmap(bitmapImage);
newUnitStatusImage.buildDrawingCache();
Bitmap bm = newUnitStatusImage.getDrawingCache();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] b = baos.toByteArray();
newUnitStatusPhoto = Base64.encodeToString(b, Base64.DEFAULT);
} catch (IOException ioEx) {
ioEx.printStackTrace();
Toast.makeText(newUnitStatusContext, "ioEx Error: " + ioEx, Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(newUnitStatusContext, "Error: " + requestCode, Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(newUnitStatusContext, "Error: " + resultCode, Toast.LENGTH_LONG).show();
}
}
public void addNewUnitStatus(String searchInput, String newUnitStatus, String generalCause, String newUnitStatusComment, String newUnitStatusPhoto, String lexaUser, String password) {
class NewUnitStatusClass extends AsyncTask<String,Void,String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = ProgressDialog.show(newUnitStatusContext, "Loading Data", null, true, true);
}
#Override
protected void onPostExecute(String httpResponseMsg) {
super.onPostExecute(httpResponseMsg);
if (httpResponseMsg != null) {
try {
JSONObject object = new JSONObject(httpResponseMsg);
message = object.getString("message");
Toast.makeText(newUnitStatusContext, httpResponseMsg, Toast.LENGTH_LONG).show();
} catch (JSONException e) {
Log.e("JSONException", "Error: " + e.toString());
Toast.makeText(newUnitStatusContext, "Error: " + e.toString(), Toast.LENGTH_LONG).show();
} // catch (JSONException e)
progressDialog.dismiss();
} else {
progressDialog.dismiss();
Toast.makeText(newUnitStatusContext, "HttpResponseMsg is null.", Toast.LENGTH_LONG).show();
}
}
#Override
protected String doInBackground(String... params) {
hashMapNewUnitStatus.put("searchinput", params[0]);
hashMapNewUnitStatus.put("newUnitStatus", params[1]);
hashMapNewUnitStatus.put("generalCause", params[2]);
hashMapNewUnitStatus.put("newUnitStatusComment", params[3]);
hashMapNewUnitStatus.put("newUnitStatusPhoto", params[4]);
hashMapNewUnitStatus.put("lexauser", params[5]);
hashMapNewUnitStatus.put("password", params[6]);
finalResultNewUnitStatus = httpParse.postRequest(hashMapNewUnitStatus, HttpURLNewUnitStatus);
return finalResultNewUnitStatus;
}
}
NewUnitStatusClass newUnitStatusClass = new NewUnitStatusClass();
newUnitStatusClass.execute(searchInput, newUnitStatus, generalCause, newUnitStatusComment, newUnitStatusPhoto, lexaUser, password);
}
}
And my code to do that actuall HttpURLConnection: HttpParse.java
package [my_package];
import android.app.ListActivity;
import android.widget.ArrayAdapter;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
public class HttpParse extends ListActivity {
String FinalHttpData = "";
String Result;
BufferedWriter bufferedWriter;
OutputStream outputStream;
BufferedReader bufferedReader;
StringBuilder stringBuilder = new StringBuilder();
URL url;
public String postRequest(HashMap<String, String> Data, String HttpUrlHolder) {
try {
url = new URL(HttpUrlHolder);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setReadTimeout(14000);
httpURLConnection.setConnectTimeout(14000);
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoInput(true);
httpURLConnection.setDoOutput(true);
outputStream = httpURLConnection.getOutputStream();
bufferedWriter = new BufferedWriter(
new OutputStreamWriter(outputStream, "UTF-8"));
bufferedWriter.write(FinalDataParse(Data));
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
if (httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
bufferedReader = new BufferedReader(
new InputStreamReader(
httpURLConnection.getInputStream()
)
);
FinalHttpData = bufferedReader.readLine();
}
else {
FinalHttpData = "Something Went Wrong";
}
} catch (Exception e) {
e.printStackTrace();
}
return FinalHttpData;
}
public String FinalDataParse(HashMap<String,String> hashMap2) throws UnsupportedEncodingException {
for(Map.Entry<String,String> map_entry : hashMap2.entrySet()){
stringBuilder.append("&");
stringBuilder.append(URLEncoder.encode(map_entry.getKey(), "UTF-8"));
stringBuilder.append("=");
stringBuilder.append(URLEncoder.encode(map_entry.getValue(), "UTF-8"));
}
Result = stringBuilder.toString();
return Result ;
}
}
All help is appreciated! Thank you!
P.S. my app shows the following error:
W/System.err: java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.length()' on a null object reference
This then leads to this:
E/JSONException: Error: org.json.JSONException: End of input at character 0 of

Upload image using base64 string, result in a broken image

I encode the image using base64 and then send to php server.
It uploaded success but result in a broken image.
No errors only a black image. May be I missing some important settings?
Upload activity
package xxxx.com.myapps;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Base64;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.ByteArrayOutputStream;
public class UploadImageActivity extends Activity {
private Button btnBrowse, btnUpload;
private AlertDialog.Builder dialogBuilder;
private ImageView imageToUpload;
private String imgPath, fileName;
String encodedString;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_upload_image);
btnBrowse = (Button) findViewById(R.id.btnBrowse);
btnUpload = (Button) findViewById(R.id.btnUpload);
imageToUpload = (ImageView) findViewById(R.id.imageToUpload);
btnBrowse.setOnClickListener(btnListener);
btnUpload.setOnClickListener(btnListener);
}
private Button.OnClickListener btnListener = new Button.OnClickListener() {
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnBrowse:
Intent galleryIntent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, Constants.PICK_IMAGE_CONTACT_REQUEST);
break;
case R.id.btnUpload:
Network network = new Network(UploadImageActivity.this);
if (network.isConnected()) {
new UploadImageAsyntask().execute();
} else {
dialogBuilder.setTitle(R.string.waring).setMessage(R.string.no_network_connection);
dialogBuilder.create();
dialogBuilder.show();
}
break;
}
}
};
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
try {
// When an Image is picked
if (requestCode == Constants.PICK_IMAGE_CONTACT_REQUEST && resultCode == RESULT_OK
&& null != data) {
// Get the Image from data
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
// Get the cursor
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
// Move to first row
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
imgPath = cursor.getString(columnIndex);
cursor.close();
// Set the Image in ImageView
imageToUpload.setImageBitmap(BitmapFactory
.decodeFile(imgPath));
// Get the Image's file name
String fileNameSegments[] = imgPath.split("/");
fileName = fileNameSegments[fileNameSegments.length - 1];
} else {
Toast.makeText(this, "You haven't picked Image",
Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG)
.show();
}
}
private class UploadImageAsyntask extends AsyncTask<Void, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(Void... params) {
Bitmap bitmap;
bitmap = BitmapFactory.decodeFile(imgPath);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
encodedString = Base64.encodeToString(byteArray,0);
String postParams = "tag=upload_new&filename=" + fileName + "&image=" + encodedString;
String jsonResult = Network.webRequest(Constants.RENOTE_DB_URL, postParams);
return jsonResult;
}
#Override
protected void onPostExecute(String jsonResult) {
super.onPostExecute(jsonResult);
// Log.d("testing", jsonResult);
}
}
}
Http Request class
package xxxx.com.myapps;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.util.Log;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class Network {
Context context;
public Network(Context context) {
this.context = context;
}
public boolean isConnected() {
ConnectivityManager cm =
(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null &&
activeNetwork.isConnectedOrConnecting();
return isConnected;
}
public static final String webRequest(String url, String postParams) {
String requestResult = null;
HttpURLConnection conn = null;
try {
URL remoteDbUrl = new URL(url);
conn = (HttpURLConnection) remoteDbUrl.openConnection();
conn.setConnectTimeout(30000);
conn.setUseCaches(false);
if (postParams != null) {
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestMethod("POST");
OutputStream outputStream = conn.getOutputStream();
outputStream.write(postParams.getBytes());
outputStream.close();
}
BufferedReader bufferedReader = new BufferedReader((new InputStreamReader(conn.getInputStream())));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = bufferedReader.readLine()) != null) {
sb.append(line);
}
bufferedReader.close();
requestResult = sb.toString();
} catch (MalformedURLException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (conn != null) {
conn.disconnect();
}
}
return requestResult;
}
}
php upload code
...
else if ($tag == 'upload_new') {
// Get image string posted from Android App
$base = $_REQUEST['image'];
// Get file name posted from Android App
$filename = $_REQUEST['filename'];
// Decode Image
$binary = base64_decode($base);
header('Content-Type: bitmap; charset=utf-8');
$file = fopen('uploadedimages/' . $filename, 'wb');
// Create File
$result = fwrite($file, $binary);
if ($result) {
echo "success";
} else {
echo "fail";
}
fclose($file);
}

Issues in Android app while sending string to Java Application

Was trying to make a simple application that receives text from speech API and send it over to a java server.Tried debugging from traces. The code does not go beyond TRY block where i opened my socket.
Code Updated : Now the application is not crashing.But no message flow.
package info.androidhive.speechtotext;
import java.io.BufferedWriter;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.Locale;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import static java.sql.DriverManager.println;
public class MainActivity extends Activity {
/**
* Declarations
*/
private TextView txtSpeechInput;
private ImageButton btnSpeak;
String str;
private final int REQ_CODE_SPEECH_INPUT = 100;
private String serverIpAddress = "";
private boolean connected = false;
TextView textIn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtSpeechInput = (TextView) findViewById(R.id.txtSpeechInput);
btnSpeak = (ImageButton) findViewById(R.id.btnSpeak);
// hide the action bar
getActionBar().hide();
btnSpeak.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
promptSpeechInput();
}
});
}
/**
* Showing google speech input dialog
*/
private void promptSpeechInput() {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());
intent.putExtra(RecognizerIntent.EXTRA_PROMPT,
getString(R.string.speech_prompt));
try {
startActivityForResult(intent, REQ_CODE_SPEECH_INPUT);
} catch (ActivityNotFoundException a) {
Toast.makeText(getApplicationContext(),
getString(R.string.speech_not_supported),
Toast.LENGTH_SHORT).show();
}
}
/**
* Receiving speech input
*/
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case REQ_CODE_SPEECH_INPUT: {
if (resultCode == RESULT_OK && null != data) {
ArrayList<String> result = data
.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
txtSpeechInput.setText(result.get(0));
str = result.get(0);
setContentView(R.layout.activity_main);
Log.d("1- naval", " client oncreate");
Button button = (Button) findViewById(R.id.send);
textIn = (TextView) findViewById(R.id.textin);
/**
* Setting the text box with default value
*/
textIn.setText(str);
Log.d("settext", " 2-naval");
/**
* Here we need to fill in textin from MainActivity,
* where we received the speech API text
*/
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
if (!connected) {
serverIpAddress = "192.168.0.4";
if (!serverIpAddress.equals("")) {
Thread cThread = new Thread(new ClientThread());
cThread.start();
}
}
}
}
);
}
}
}
}
public class ClientThread implements Runnable {
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName(serverIpAddress);
Log.d("ClientActivity", "C: Connecting...");
Socket socket = new Socket(serverAddr, 8888);
PrintWriter out = null;
out.println(str);
connected = true;
while (connected) {
try {
Log.d("ClientActivity", "C: Sending command.");
out = new PrintWriter(
new BufferedWriter(new OutputStreamWriter(
socket.getOutputStream())), true);
// WHERE YOU ISSUE THE COMMANDS
// out.println("Hey Server!");
Log.d("ClientActivity", "C: Sent.");
} catch (Exception e) {
Log.e("ClientActivity", "S: Error", e);
}
}
socket.close();
Log.d("ClientActivity", "C: Closed.");
} catch (Exception e) {
Log.e("ClientActivity", "C: Error", e);
connected = false;
}
}
}
}
Since, at the time of writing this answer, the author has yet to add a stacktrace I'll go over some basic solutions:
Make sure you've added INTERNET permission to your android manifest, otherwise your socket wont open <uses-permission android:name="android.permission.INTERNET" />
Open your socket on a background thread. Networking on the UI thread (eg. inside the onClick method) is prohibited on android
Add a stack trace if the above didn't solve your problem

How to use variables in other classes

Im a little lost on this. Trying to pass variables onto another class for output. This class gets the variable.
OneWeekPlan_Start_Btn.java
package com.th3ramr0d.prtmanager;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class OneWeekPlan_Start_Btn extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.oneweek_day1);
EditText inputTxt = (EditText) findViewById(R.id.wkOneDayOneInstructorName);
String wk1day1_inst = inputTxt.getText().toString();
Button oneweekDay2 = (Button) findViewById(R.id.wk1Day2);
oneweekDay2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
startActivity(new Intent("com.th3ramr0d.prtmanager.ONEWEEKDAYTWO"));
}
});
}
}
I want to be able to use the variable wk1day1_inst in the following class
Save_File.java
package com.th3ramr0d.prtmanager;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import android.content.Context;
import android.os.Environment;
import android.util.Log;
import android.view.View.OnClickListener;
public class Save_File extends Activity implements OnClickListener{
Button writeExcelButton;
static String TAG = "ExelLog";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.save_file);
writeExcelButton = (Button) findViewById(R.id.wk1Save);
writeExcelButton.setOnClickListener(this);
}
public void onClick(View v)
{
EditText inputTxt = (EditText) findViewById(R.id.wkOneSaveFile);
String fileName = inputTxt.getText().toString();
switch (v.getId())
{
case R.id.wk1Save:
saveExcelFile(this,fileName + ".xls");
}
setContentView(R.layout.created);
}
private static boolean saveExcelFile(Context context, String fileName) {
// check if available and not read only
if (!isExternalStorageAvailable() || isExternalStorageReadOnly()) {
Log.e(TAG, "Storage not available or read only");
return false;
}
boolean success = false;
//New Workbook
Workbook wb = new HSSFWorkbook();
Cell c1 = null;
//Cell style for header row
CellStyle cs = wb.createCellStyle();
cs.setFillForegroundColor(HSSFColor.LIME.index);
cs.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
//New Sheet
Sheet sheet1 = null;
sheet1 = wb.createSheet("My PT Plan");
// Generate column headings
Row row = sheet1.createRow(0);
c1 = row.createCell(0);
c1.setCellValue("FUCK YOU SCIENCE!");
c1.setCellStyle(cs);
c1 = row.createCell(1);
c1.setCellValue("Quantity");
c1.setCellStyle(cs);
c1 = row.createCell(2);
c1.setCellValue("Price");
c1.setCellStyle(cs);
sheet1.setColumnWidth(0, (15 * 500));
sheet1.setColumnWidth(1, (15 * 500));
sheet1.setColumnWidth(2, (15 * 500));
// Create a path where we will place our List of objects on external storage
File file = new File(context.getExternalFilesDir(null), fileName);
FileOutputStream os = null;
try {
os = new FileOutputStream(file);
wb.write(os);
Log.w("FileUtils", "Writing file" + file);
success = true;
} catch (IOException e) {
Log.w("FileUtils", "Error writing " + file, e);
} catch (Exception e) {
Log.w("FileUtils", "Failed to save file", e);
} finally {
try {
if (null != os)
os.close();
} catch (Exception ex) {
}
}
return success;
}
public static boolean isExternalStorageReadOnly() {
String extStorageState = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(extStorageState)) {
return true;
}
return false;
}
public static boolean isExternalStorageAvailable() {
String extStorageState = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(extStorageState)) {
return true;
}
return false;
}
}
More specifically I want to be able to use that variable for the spreadsheet. ie
c1 = row.createCell(0);
c1.setCellValue(wk1day1_inst);
c1.setCellStyle(cs);
Thanks for any help!
You can pass data between two activities using Intent.
Intent intent = new Intent (OneWeekPlan_Start_Btn.this, Save_File.class);
intent.putExtra("wk1day1_inst", wk1day1_ins);
startActivity(intent);
And in your next Activity, use this:
String wk1day1_inst = getIntent().getStringExtra("wk1day1_inst");
Hope this helps.
You can use SharedPreferences to save value of variable. It's advantage over putExtra of Intent is that with SharedPreferences the value of variable can be accessed inside any activity while Intent only allows to access variable in 1 activity.
//Save the value in OneWeekPlan_Start_Btn class
SharedPreferences.Editor editor = settings.edit();
editor.putString("weekday", wk1day1_inst);
editor.commit();
//Access the value in Save_File class
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
String wk1day = settings.getString("weekday", "");

Getting exeception while executing my android app on emulator. (But its working fine on phone)

Getting this exception while executing on emulator.
I think this is related to some memory issue.
Because its working fine when am trying it on my phone.
Anyone help me to find the real reason for this problem?
Galleryview.java
package example.hitwallhd;
import example.hitwallhd.ImageDownloader;
import example.hitwallhd.ImageDownloader.ImageLoaderListener;
import example.hitwallhd.R;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URISyntaxException;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ImageView.ScaleType;
public class Galleryview extends Activity {
private ProgressBar pb;
private Button save,bnxt,bprv;
private ImageView img;
private static Bitmap bmp;
private TextView percent;
private FileOutputStream fos;
private ImageDownloader mDownloader;
TextView t1,t2;
String num,cate,addrs,urladdrs,pviews,pdown,sele;
int savecount=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_galleryview);
save.setEnabled(false);
initViews();
Bundle extras = getIntent().getExtras();
num = extras.getString("num");
cate = extras.getString("category");
sele = extras.getString("sele");
addrs= extras.getString("picno");
t1 =(TextView) findViewById(R.id.textView2);
t2 =(TextView) findViewById(R.id.textView3);
//t1.setText(pviews);
//t2.setText(pdown);
urladdrs="http://someaddrs.com/wallpapers/"+cate+"/"+addrs;
/*--- instantiate our downloader passing it required components ---*/
mDownloader = new ImageDownloader(urladdrs, pb, save, img, percent, Galleryview.this, bmp, new ImageLoaderListener() {
#Override
public void onImageDownloaded(Bitmap bmp) {
Galleryview.bmp = bmp;
/*--- here we assign the value of bmp field in our Loader class
* to the bmp field of the current class ---*/
}
});
/*--- we need to call execute() since nothing will happen otherwise ---*/
mDownloader.execute();
save.setEnabled(true);
}
private void initViews() {
save = (Button) findViewById(R.id.save);
//bnxt=(Button) findViewById(R.id.bnext);
//bprv=(Button) findViewById(R.id.bprev);
/*--- we are using 'this' because our class implements the OnClickListener ---*/
img = (ImageView) findViewById(R.id.imageView1);
img.setScaleType(ScaleType.CENTER_CROP);
pb = (ProgressBar) findViewById(R.id.pbDownload);
pb.setVisibility(View.INVISIBLE);
percent = (TextView) findViewById(R.id.textView1);
percent.setVisibility(View.INVISIBLE);
}
public void onclick_next(View v)
{
bprv.setEnabled(true);
GetData obj = new GetData();
int nxt=Integer.parseInt(num)+1;
num=String.valueOf(nxt);
String urls="http://someaddrs.com/wallpapers/newlist.php?cate="+cate+"&no="+num+"&prev=0";
obj.execute(urls);
}
public void onclick_prev(View v)
{
bnxt.setEnabled(true);
GetData obj = new GetData();
int nxt=Integer.parseInt(num)-1;
num=String.valueOf(nxt);
String urls="http://someaddrs.com/wallpapers/newlist.php?cate="+cate+"&no="+num+"&prev=1";
obj.execute(urls);
}
public void onclick_save(View v)
{
saveImageToSD();
String cnum;
if(urladdrs.equals("nexterror"))
{
int nxt=Integer.parseInt(num)-1;
cnum=String.valueOf(nxt);
}
else if(urladdrs.equals("preverror"))
{
int nxt=Integer.parseInt(num)+1;
cnum=String.valueOf(nxt);
}
else
cnum=num;
savecount=1;
GetData obj = new GetData();
String urls="http://someaddrs.com/wallpapers/downloadcount.php?no="+cnum;
obj.execute(urls);
}
private void saveImageToSD() {
/*--- this method will save your downloaded image to SD card ---*/
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
/*--- you can select your preferred CompressFormat and quality.
* I'm going to use JPEG and 100% quality ---*/
bmp.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
/*--- create a new file on SD card ---*/
File file = new File(Environment.getExternalStorageDirectory()
+ File.separator + num+"Image.jpg");
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
/*--- create a new FileOutputStream and write bytes to file ---*/
try {
fos = new FileOutputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
fos.write(bytes.toByteArray());
fos.close();
Toast.makeText(this, "Image saved", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
}
Intent pview = new Intent(Galleryview.this,HitWall.class);
startActivity(pview);
}
public void looperfn()
{
t1 =(TextView) findViewById(R.id.textView2);
t2 =(TextView) findViewById(R.id.textView3);
t1.setText(pviews);
t2.setText(pdown);
if(urladdrs.equals("nexterror"))
{
int nxt=Integer.parseInt(num)-1;
num=String.valueOf(nxt);
bnxt.setEnabled(false);
}
else if(urladdrs.equals("preverror"))
{
int nxt=Integer.parseInt(num)+1;
num=String.valueOf(nxt);
bprv.setEnabled(false);
}
else
{
//t1.setText(urladdrs);
urladdrs="http://someaddrs.com/wallpapers/"+cate+"/"+urladdrs;
mDownloader = new ImageDownloader(urladdrs, pb, save, img, percent, Galleryview.this, bmp, new ImageLoaderListener() {
#Override
public void onImageDownloaded(Bitmap bmp) {
Galleryview.bmp = bmp;
/*--- here we assign the value of bmp field in our Loader class
* to the bmp field of the current class ---*/
}
});
/*--- we need to call execute() since nothing will happen otherwise ---*/
mDownloader.execute();
}
}
public class GetData extends AsyncTask<String, Void, String>{
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
BufferedReader reader =null;
String data =null;
try{
HttpClient client = new DefaultHttpClient();
URI uri=new URI(params[0]);
HttpGet get =new HttpGet(uri);
HttpResponse response= client.execute(get);
InputStream stream=response.getEntity().getContent();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer =new StringBuffer("");
String line="";
while((line=reader.readLine())!=null){
buffer.append(line);
}
reader.close();
data = buffer.toString();
if(data.equals("preverror")||data.equals("nexterror"))
{
return data;
}
else
{
pviews=data.substring(data.indexOf("|")+1,data.indexOf(":"));
pviews=" Views : "+pviews;
pdown=data.substring(data.indexOf(":")+1, data.length());
pdown=" Downloads : "+pdown;
data=data.substring(0, data.indexOf("|"));
return data;
}
//data=data.substring(0, data.indexOf("|"));
//t1.setText(data);
}
catch(URISyntaxException e){
e.printStackTrace();
}
catch(ClientProtocolException f){
f.printStackTrace();
}
catch(IOException g){
g.printStackTrace();
}
finally{
if(reader!=null){
try{
reader.close();
}
catch(Exception e){
}
}
}
return null;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
urladdrs=result;
if(savecount==0)
{
looperfn();
}
else
savecount=0;
}
}
}
This type of issue is arrived due to memory leakage.
the main problem is that there is Java.lang.NullPointerException and this type of exception arrives when there is low virtual memory.
As there is low virtual memory in emulator so it is getting the error and the phone has the sufficient virtual memory to display and load the image in the memory.
You have an exception in Galleryview.java at line 57. Please provide the peace of code around line 57 or the whole Galleryview.java.

Categories