My app has no error line, but when i run on emulator, it comes with an error the application Koperasidb (process.com.randy.koperasidb) has stopped unexpectedly Please try again please help, here's my login.java code:
package com.randy.koperasidb;
import android.app.Activity;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class login extends Activity implements OnClickListener{
EditText kode,pw;
TextView error;
Button login;
String i;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
kode = (EditText) findViewById(R.id.kode);
pw = (EditText) findViewById (R.id.password);
login = (Button) findViewById (R.id.login);
error = (EditText) findViewById (R.id.error);
login.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch(v.getId()){
case R.id.login:
insert();
}
}
public void insert(){
String i= "http://10.0.2.2/mysql/insert.php";
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(i);
ArrayList<NameValuePair> param = new ArrayList<NameValuePair>();
param.add(new BasicNameValuePair("kode", kode.getText().toString()));
param.add(new BasicNameValuePair("password", pw.getText().toString()));
try {
httpPost.setEntity(new UrlEncodedFormEntity(param));
HttpResponse httpRespose = httpClient.execute(httpPost);
HttpEntity httpEntity = httpRespose.getEntity();
InputStream in = httpEntity.getContent();
BufferedReader read = new BufferedReader(new InputStreamReader(in));
String isi= "";
String baris= "";
while((baris = read.readLine())!=null){
isi+= baris;
}
if(!isi.equals("null")){
Toast.makeText(this, "Berhasil", Toast.LENGTH_LONG).show();
}else{
Toast.makeText(this, "Gagal", Toast.LENGTH_LONG).show();
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
here's my login.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#ff00ffff"
>
<TableLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:text="Selamat datang di Puskopdit Jakarta"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColor="#ff0000ff"
/>
<TextView
android:text="Input Kode Anggota"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColor="#ff0000ff"
/>
<EditText
android:id="#+id/kode"
android:layout_width="150px"
android:layout_height="wrap_content"
android:gravity="center"
android:layout_gravity="center"
android:hint="Kode Anggota"
/>
<TextView
android:text="Input Password"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColor="#ff0000ff"
/>
<EditText
android:id="#+id/password"
android:layout_width="150px"
android:layout_height="wrap_content"
android:gravity="center"
android:layout_gravity="center"
android:hint="Password"
/>
<Button
android:id="#+id/login"
android:layout_width="200px"
android:layout_height="wrap_content"
android:gravity="center"
android:layout_gravity="center"
android:textColor="#ffffffff"
/>
<TextView
android:text=""
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColor="#ff0000ff"
android:id="#+id/error"
/>
</TableLayout>
</LinearLayout>
and here's my AndroidManifest.xml file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.randy.koperasidb"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="#drawable/icon" android:label="#string/app_name">
<activity android:name=".login"
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>
<uses-sdk android:minSdkVersion="9" />
<uses-permission android:name="android.permission.INTERNET"/>
</manifest>
Related
I working on a weather channel app with API and JSON. I wrote all the code but it doesn't work, any help would be appreciated. The API for my app is from https://openweathermap.org/ and I ran it through Postman.
Here is my activity_main.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">
<TextView
android:id="#+id/t1_temp"
android:layout_width="124dp"
android:layout_height="133dp"
android:text="30"
android:textSize="100dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintHorizontal_bias="0.055"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.17" />
<TextView
android:id="#+id/t2_city"
android:layout_width="130dp"
android:layout_height="25dp"
android:text="My City"
android:textSize="15dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintHorizontal_bias="1.0"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.069" />
<TextView
android:id="#+id/t3_description"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Sunny"
android:textSize="15dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintHorizontal_bias="0.043"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.33" />
<TextView
android:id="#+id/t4_date"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Date"
android:textSize="15dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintHorizontal_bias="0.041"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.075" />
<TextView
android:id="#+id/t5_C"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="C"
android:textSize="30dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintHorizontal_bias="0.349"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.143" />
</androidx.constraintlayout.widget.ConstraintLayout>
Here is my MainActivity.java:
package com.example.weatherchannel;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
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 org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.text.SimpleDateFormat;
import java.util.Calendar;
public class MainActivity extends AppCompatActivity {
TextView t1_temp,t2_city,t3_description,t4_date;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
t1_temp = findViewById(R.id.t1_temp);
t2_city = findViewById(R.id.t2_city);
t3_description = findViewById(R.id.t3_description);
t4_date = findViewById(R.id.t4_date);
find_weather();
}
public void find_weather() {
String url = "http://api.openweathermap.org/data/2.5/weather?q=kirkkonummi,finland&appid=48c0eb71736c9d90039d04e5c83581a0&units=metric";
JsonObjectRequest jor = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONObject main_object = response.getJSONObject("main");
JSONArray array = response.getJSONArray("weather");
JSONObject object = array.getJSONObject(0);
String temp = String.valueOf(main_object.getDouble("temp"));
String description = object.getString("description");
String city = response.getString("name");
//t1_temp.setText(temp);
t2_city.setText(city);
t3_description.setText(description);
Calendar calendar = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("EEEE=MM-dd");
String formatted_date = sdf.format(calendar.getTime());
t4_date.setText(formatted_date);
double temp_int = Double.parseDouble(temp);
double centi = (temp_int - 32) / 1.8000;
centi = Math.round(centi);
int i = (int) centi;
t1_temp.setText(String.valueOf(i));
}catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}
);
RequestQueue queue = Volley.newRequestQueue(this);
queue.add(jor);
}
}
and here is my AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.weatherchannel">
<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/AppTheme">
<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>
If more information is needed just ask.
I found the answer, my API url wasn't working so I changed it to
https://samples.openweathermap.org/data/2.5/weather?q=London,uk&appid=48c0eb71736c9d90039d04e5c83581a0
although this is not the correct API, now I just know that my app works correctly, I just have to get the correct API for my location.
I'm trying here to make a project, that can scan a barcode (that is done), and after that it's supposed to show some values from a database based on that barcode (product name, address).
I manage to copy the value from the barcode to the clipboard, but then I cannot manage to copy it to the activity_second.xml's EditText.
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="br.exemplozxingintegration"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="19" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.FLASHLIGHT" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="com.android.browser.permission.READ_HISTORY_BOOKMARKS" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="ScannerBucatarie"
android:theme="#style/AppTheme">
<activity
android:name=".MainActivity"
android:label="ScannerBucatarie"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.google.zxing.client.android.CaptureActivity"
android:configChanges="orientation|keyboardHidden"
android:label="ZXing ScanBar"
android:theme="#android:style/Theme.NoTitleBar.Fullscreen"
android:windowSoftInputMode="stateAlwaysHidden">
<intent-filter>
<action android:name="com.google.zxing.client.android.SCAN" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity
android:name=".SecondActivity"
android:label="#string/title_activity_second"></activity>
</application>
</manifest>
Config.java
package br.exemplozxingintegration;
/**
* Created by Boghy on 09.02.2016.
*/
public class Config {
public static final String DATA_URL = "http://192.168.94.1/test/getData.php?id=";
public static final String KEY_NAME = "name";
public static final String KEY_ADDRESS = "address";
public static final String KEY_VC = "vc";
public static final String JSON_ARRAY = "result";
}
SecondActivity.java
package br.exemplozxingintegration;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class SecondActivity extends AppCompatActivity implements View.OnClickListener {
private EditText editTextId;
private Button buttonGet;
private TextView textViewResult;
private ProgressDialog loading;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editTextId = (EditText) findViewById(R.id.editTextId);
buttonGet = (Button) findViewById(R.id.buttonGet);
textViewResult = (TextView) findViewById(R.id.textViewResult);
buttonGet.setOnClickListener(this);
}
private void getData() {
String id = editTextId.getText().toString().trim();
if (id.equals("")) {
Toast.makeText(this, "Please enter an id", Toast.LENGTH_LONG).show();
return;
}
loading = ProgressDialog.show(this,"Please wait...","Fetching...",false,false);
String url = Config.DATA_URL+editTextId.getText().toString().trim();
StringRequest stringRequest = new StringRequest(url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
loading.dismiss();
showJSON(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(SecondActivity.this,error.getMessage().toString(),Toast.LENGTH_LONG).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
private void showJSON(String response){
String name="";
String address="";
String vc = "";
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray result = jsonObject.getJSONArray(Config.JSON_ARRAY);
JSONObject collegeData = result.getJSONObject(0);
name = collegeData.getString(Config.KEY_NAME);
address = collegeData.getString(Config.KEY_ADDRESS);
vc = collegeData.getString(Config.KEY_VC);
} catch (JSONException e) {
e.printStackTrace();
}
textViewResult.setText("Name:\t"+name+"\nAddress:\t" +address+ "\nVice Chancellor:\t"+ vc);
}
#Override
public void onClick(View v) {
getData();
}
}` AndroidManifet.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="br.exemplozxingintegration"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="19" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.FLASHLIGHT" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="com.android.browser.permission.READ_HISTORY_BOOKMARKS" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
Config.java
package br.exemplozxingintegration;
/**
* Created by Boghy on 09.02.2016.
*/
public class Config {
public static final String DATA_URL = "http://192.168.94.1/test/getData.php?id=";
public static final String KEY_NAME = "name";
public static final String KEY_ADDRESS = "address";
public static final String KEY_VC = "vc";
public static final String JSON_ARRAY = "result";
}
activity_second.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:orientation="vertical"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".SecondActivity">
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:id="#+id/txResult"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"/>
<Button
android:id="#+id/buttonGet"
android:text="Get"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
<TextView
android:id="#+id/textViewResult"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</LinearLayout>
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:weightSum="1">
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
android:background="#ddd" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Scan"
android:onClick="callZXing"
android:id="#+id/Button" />
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
android:background="#ddd" />
<TextView
android:id="#+id/txResult"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Rezultat:"
android:textSize="20sp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Is this the correct code?"
android:id="#+id/textView"
android:layout_marginTop="70dp"
android:layout_gravity="center_horizontal" />
<Button
style="#style/CaptureTheme"
android:layout_width="112dp"
android:layout_height="68dp"
android:text="Yes"
android:layout_marginTop="30dp"
android:id="#+id/button2"
android:layout_weight="0.10"
android:layout_gravity="center_horizontal"
android:onClick="sendSecond" />
<Button
style="#style/CaptureTheme"
android:layout_width="112dp"
android:layout_height="68dp"
android:text="No"
android:layout_marginTop="10dp"
android:id="#+id/button1"
android:layout_weight="0.10"
android:layout_gravity="center_horizontal"
android:onClick="callZXing" />
</LinearLayout>
SecondActivity.java
package br.exemplozxingintegration;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class SecondActivity extends AppCompatActivity implements View.OnClickListener {
private EditText editTextId;
private Button buttonGet;
private TextView textViewResult;
private ProgressDialog loading;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editTextId = (EditText) findViewById(R.id.editTextId);
buttonGet = (Button) findViewById(R.id.buttonGet);
textViewResult = (TextView) findViewById(R.id.textViewResult);
buttonGet.setOnClickListener(this);
}
private void getData() {
String id = editTextId.getText().toString().trim();
if (id.equals("")) {
Toast.makeText(this, "Please enter an id", Toast.LENGTH_LONG).show();
return;
}
loading = ProgressDialog.show(this,"Please wait...","Fetching...",false,false);
String url = Config.DATA_URL+editTextId.getText().toString().trim();
StringRequest stringRequest = new StringRequest(url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
loading.dismiss();
showJSON(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(SecondActivity.this,error.getMessage().toString(),Toast.LENGTH_LONG).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
private void showJSON(String response){
String name="";
String address="";
String vc = "";
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray result = jsonObject.getJSONArray(Config.JSON_ARRAY);
JSONObject collegeData = result.getJSONObject(0);
name = collegeData.getString(Config.KEY_NAME);
address = collegeData.getString(Config.KEY_ADDRESS);
vc = collegeData.getString(Config.KEY_VC);
} catch (JSONException e) {
e.printStackTrace();
}
textViewResult.setText("Name:\t"+name+"\nAddress:\t" +address+ "\nVice Chancellor:\t"+ vc);
}
#Override
public void onClick(View v) {
getData();
}
}
In your main activity, set your data into Intent as below:
Intent intent = getIntent();
intent.putExtra("Param_name", txtNumOfCards.getText().toString());
intent.setClass(this, SecondActivity.class);
startActivity(intent);
In the second activity, you can retrieve it as below:
Intent intent = getIntent();
String value = intent.getStringExtra("Param_name");
Checkout the following exmaple:
http://www.startandroid.ru/en/lessons/complete-list/241-lesson-28-extras-passing-data-using-intent.html
As #Mohammed Kharma explained, you must send the id as an Intent extra (no need to copy it to the clipboard). I believe you already created this Intent, but I'm recreating it. Have in mind that I don't know the name you chose for your intent, so I'll just call it 'i'.
On your MainActivity.java:
Intent i= new Intent(MainActivity.class,SecondActivity.java);
i.putExtra("barcode",txtResult.getText().toString());
startActivity(i);
On your SecondActivity.java:
textViewResult = (TextView) findViewById(R.id.textViewResult);
String barcode=getIntent().getStringExtra("barcode");
textViewResult.setText(barcode);
I've looked at a bunch of posts on this subject, but nothing seems to be working and I've been stuck on this problem for 2 days now. these lines of code are getting red underline on the "R" saying it cannot be resolved as a variable
symbols = (EditText) findViewById(R.id.editText1);
results = (TextView) findViewById(R.id.textView2);
Button button = (Button) findViewById(R.id.button1);
Also this line of code at the bottom of the java file has the same error
getMenuInflater().inflate(R.menu.activity_main, menu);
I created a menu folder under res and a menu.xml file as well.
Here's all the code and a screenshot of my environment. I'm not sure which file you need to see so I provided them all just in case.
Screenshot of Environment
http://postimg.org/image/6d1l0909r/
MainActivity.Java
package com.example.stocks;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.Button;
import android.view.View.OnClickListener;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import java.net.HttpURLConnection;
import java.net.URL;
import java.io.InputStreamReader;
import java.io.IOException;
import java.io.BufferedReader;
import java.net.MalformedURLException;
import android.os.Handler;
public class MainActivity extends Activity implements Runnable {
String symbolsStr = "";
String resultsStr = "";
EditText symbols = null;
TextView results = null;
final Handler mHandler = new Handler();
final Runnable mUpdateResults = new Runnable() {
public void run() {
results.setText(resultsStr);
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
symbols = (EditText) findViewById(R.id.editText1);
results = (TextView) findViewById(R.id.textView2);
Button button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
symbolsStr = symbols.getText().toString();
Thread thread = new Thread(MainActivity.this);
thread.start();
}
});
}
#Override
public void run() {
try {
resultsStr = GetQuotes(symbolsStr);
mHandler.post(mUpdateResults);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private String GetQuotes(String symbols) throws MalformedURLException,
IOException {
StringBuilder response = new StringBuilder();
// call web service to get results
String urlStr = "http://download.finance.yahoo.com/d/quotes.csv?s="
+ symbols + "&f=nsl1op";
URL url = new URL(urlStr);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
BufferedReader input = new BufferedReader(new InputStreamReader(
httpConn.getInputStream()), 8192);
String strLine = null;
while ((strLine = input.readLine()) != null) {
response.append(strLine);
response.append("\n");
}
input.close();
}
return response.toString();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
activity_main.xml
<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=".MainActivity" >
<TextView
android:id="#+id/textView1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="22dp"
android:layout_marginTop="44dp"
android:text="Enter Symbols separated by commas:" />
<EditText
android:id="#+id/editText1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView1"
android:layout_below="#+id/textView1"
android:layout_marginTop="16dp"
android:ems="10" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/editText1"
android:layout_below="#+id/editText1"
android:layout_marginTop="44dp"
android:text="Look Up" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/button1"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_below="#+id/button1"
android:layout_marginTop="33dp"
android:text="Results" />
</RelativeLayout>
strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">StockQuotes</string>
<string name="hello_world">Hello world!</string>
<string name="menu_settings">Settings</string>
</resources>
menu.xml
<?xml version="1.0" encoding="UTF-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="#+id/item1"></item>
<item android:id="#+id/item2"></item>
<item android:id="#+id/item3"></item>
</menu>
android manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.stockquotes"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="16" />
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.stockquotes.MainActivity"
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>
Your packages mismatch:
In Activity: package com.example.stocks;
In Manifest:
package="com.example.stockquotes"
Use 1 of them and rebuild your project.
I am trying to send some commands over telnet.
Everything works fine when executed locally on a PC on basis of a swing GUI, but when using the same code on Android, the app freezes for a few seconds and the commands are not carried out (same result on emulator and real device), although it runs to the end. No error message is being thrown, but after this procedure the device is not reachable via Telnet, not even via PC (restart of target device is then necessary). What I do not understand is that it seems that the 500 milliseconds restriction I set is being ignored on Android.
I am a novice on Android so please bear with me. Glad for any help.
package com.test.test.remote;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetSocketAddress;
import java.net.Socket;
import android.os.Bundle;
import android.os.StrictMode;
import android.app.Activity;
import android.util.Log;
import android.view.View;
public class MainActivity extends Activity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
setContentView(R.layout.activity_main);
}
public void calculate(View view) throws Exception {
System.out.println("Calc button executed");
command("MO");
}
public String command(String cmd) {
String output = "test";
Log.e("Msg", "command reached");
Log.e("Msg", cmd);
Socket pingSocket = null;
PrintWriter out = null;
BufferedReader in = null;
pingSocket = new Socket();
try {
pingSocket.connect(new InetSocketAddress("10.10.10.107", 23), 500);
out = new PrintWriter(pingSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(
pingSocket.getInputStream()));
out.println(cmd);
output = in.readLine();
out.close();
in.close();
pingSocket.close();
System.out.println(output);
Log.e("Msg", "end of command reached");
} catch (Exception e) {
Log.e("com.example.test.MainActivity", e.getMessage());
e.printStackTrace();
}
return output;
}
}
XML:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<EditText
android:id="#+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="24dp"
android:layout_marginTop="31dp"
android:ems="10"
android:inputType="numberDecimal|numberSigned" >
<requestFocus />
</EditText>
<RadioGroup
android:id="#+id/radioGroup1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/editText1"
android:layout_below="#+id/editText1"
android:layout_marginTop="28dp" >
<RadioButton
android:id="#+id/radio0"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:text="#string/kmh" />
</RadioGroup>
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/radioGroup1"
android:layout_centerVertical="true"
android:onClick="calculate"
android:text="#string/calc" />
</RelativeLayout>
Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.test.test.remote"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="9"
android:targetSdkVersion="21" />
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
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>
can someone help me plsss, the error message comes in the textbox on the login form, the error is when i submit my information on the first form it won't go to database instead showing error "error java.net.socketException: permission denied" here's my code:
tambah_user.java
package com.wilis.hellomysql;
import java.util.ArrayList;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.TextView;
public class tambah_user extends Activity {
EditText un,pw,rpw,nl,al,nt,nh;
RadioGroup jk;
TextView error;
Button simpan,keluar;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tambah_user);
un=(EditText)findViewById(R.id.et_un);
pw=(EditText)findViewById(R.id.et_pw);
rpw=(EditText)findViewById(R.id.et_rpw);
nl=(EditText) findViewById(R.id.et_nama);
jk=(RadioGroup) findViewById(R.id.jekel);
al=(EditText) findViewById(R.id.et_alamat);
nt=(EditText) findViewById(R.id.et_notel);
nh=(EditText) findViewById(R.id.et_nohp);
simpan=(Button)findViewById(R.id.btn_simpan);
keluar=(Button)findViewById(R.id.btn_keluar);
error=(TextView)findViewById(R.id.error);
simpan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//atur variabel utk menampung pilihan jenis kelamin
String type=null;
switch (jk.getCheckedRadioButtonId()) {
case R.id.pria:
type="Pria";
break;
case R.id.perempuan:
type="Perempuan";
break;
}
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("username", un.getText().toString()));
postParameters.add(new BasicNameValuePair("password", pw.getText().toString()));
postParameters.add(new BasicNameValuePair("repassword", rpw.getText().toString()));
postParameters.add(new BasicNameValuePair("nama", nl.getText().toString()));
postParameters.add(new BasicNameValuePair("jekel", type));
postParameters.add(new BasicNameValuePair("alamat", al.getText().toString()));
postParameters.add(new BasicNameValuePair("nomor_tlp", nt.getText().toString()));
postParameters.add(new BasicNameValuePair("nomor_hp", nh.getText().toString()));
/* String valid = "1";*/
String response = null;
try {
response = CustomHttpClient.executeHttpPost("http://10.0.2.2/appmysql/simpan.php", postParameters);
String res = response.toString();
res = res.trim();
res = res.replaceAll("\\s+","");
error.setText(res);
if (res.equals("1")) error.setText("Data Tersimpan");
else error.setText("Data Tersimpan Ke server");
}
catch (Exception e) {
un.setText(e.toString());
}
}
});
}
public void keluar (View theButton)
{
}
}
CustomHttpClient.java
package com.wilis.hellomysql;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.util.ArrayList;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
public class CustomHttpClient {
public static final int HTTP_TIMEOUT = 30 * 1000; // milliseconds
private static HttpClient mHttpClient;
private static HttpClient getHttpClient() {
if (mHttpClient == null) {
mHttpClient = new DefaultHttpClient();
final HttpParams params = mHttpClient.getParams();
HttpConnectionParams.setConnectionTimeout(params, HTTP_TIMEOUT);
HttpConnectionParams.setSoTimeout(params, HTTP_TIMEOUT);
ConnManagerParams.setTimeout(params, HTTP_TIMEOUT);
}
return mHttpClient;
}
public static String executeHttpPost(String url, ArrayList<NameValuePair> postParameters) throws Exception {
BufferedReader in = null;
try {
HttpClient client = getHttpClient();
HttpPost request = new HttpPost(url);
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters);
request.setEntity(formEntity);
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
String result = sb.toString();
return result;
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static String executeHttpGet(String url) throws Exception {
BufferedReader in = null;
try {
HttpClient client = getHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI(url));
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
String result = sb.toString();
return result;
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
tambah_user.xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#ff00ffff"
>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:text="Silakan Masukkan Data Pengguna"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textColor="#ff0000ff"
/>
<TableRow android:baselineAligned="true" android:layout_width="match_parent">
<TextView
android:text="Username:"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#ff0000ff"
/>
<EditText android:id="#+id/et_un"
android:maxWidth="140sp"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:layout_gravity="center_vertical" >
</EditText>
</TableRow>
<TableRow>
<TextView
android:text="Password:"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#ff0000ff"
/>
<EditText android:id="#+id/et_pw"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:layout_gravity="center_vertical"
android:inputType="textPassword">
</EditText>
</TableRow>
<TableRow>
<TextView
android:text="retype-Password:"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#ff0000ff"
/>
<EditText android:layout_height="wrap_content"
android:id="#+id/et_rpw"
android:layout_width="match_parent"
android:inputType="textPassword">
</EditText>
</TableRow>
<TableRow>
<TextView
android:text="Nama Lengkap:"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#ff0000ff"
/>
<EditText android:layout_height="wrap_content"
android:id="#+id/et_nama"
android:layout_width="match_parent">
</EditText>
</TableRow>
<TableRow>
<TextView android:text="Jekel:"
android:textColor="#ff0000ff"/>
<RadioGroup android:id="#+id/jekel">
<RadioButton android:id="#+id/pria"
android:text="Pria"
/>
<RadioButton android:id="#+id/perempuan"
android:text="Perempuan"
/>
</RadioGroup>
</TableRow>
<TableRow>
<TextView
android:text="Alamat:"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#ff0000ff"
/>
<EditText android:layout_height="wrap_content"
android:id="#+id/et_alamat"
android:layout_width="match_parent">
</EditText>
</TableRow>
<TableRow>
<TextView
android:text="Nomor Tlp:"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#ff0000ff"
/>
<EditText android:layout_height="wrap_content"
android:id="#+id/et_notel"
android:layout_width="match_parent">
</EditText>
</TableRow>
<TableRow>
<TextView
android:text="Nomor HP:"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#ff0000ff"
/>
<EditText android:layout_height="wrap_content"
android:id="#+id/et_nohp"
android:layout_width="match_parent">
</EditText>
</TableRow>
<TableRow >
<Button android:text="S I M P A N"
android:id="#+id/btn_simpan"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</Button>
<Button android:text="K E L U A R"
android:id="#+id/btn_keluar"
android:onClick="keluar"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</Button>
</TableRow>
<TextView
android:text=""
android:id="#+id/error"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#ff0000ff"
/>
</TableLayout>
</ScrollView>
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.wilis.hellomysql"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="#drawable/icon" android:label="#string/app_name">
<activity android:name=".tambah_user"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".CustomHttpClient" android:label="#string/app_name">
</activity>
</application>
<uses-sdk android:minSdkVersion="8" />
</manifest>
You have to add the internet permission to you manifiest file:
<uses-permission android:name="android.permission.INTERNET" />
And also Android wont let you do http connections in the main thread, for more info look up:
http://developer.android.com/reference/android/os/AsyncTask.html
You have forgotten the internet permission in your manifest file.
<uses-permission android:name="android.permission.INTERNET" />
After that you will get an networkonmainthreadexception because you are doing web request in the main thread.
Use another AsyncTask or another thread for that.
You did forget too add
<uses-permission android:name="android.permission.INTERNET" />
in your manifest.xml.
But after that you will receive a networkmainthreadexception, to avoid this you need to use AsyncTask or an extra thread. If you get problems to use this things you read this post which may helps you.